
本教程旨在解决使用python爬取yahoo财经动态加载收益数据时遇到的挑战。传统基于`beautifulsoup`的静态html解析方法在此类场景中无效。文章将详细指导如何通过模拟浏览器对yahoo财经后端api的post请求,获取包含公司名称、事件类型和发布时间等详细收益信息的结构化json数据,并提供了完整的python代码示例及注意事项。
在尝试从Yahoo财经等现代网站抓取数据时,开发者常会遇到一个问题:即使使用requests库成功获取了页面内容,BeautifulSoup也无法找到预期的元素。这通常是因为网站采用了JavaScript动态加载数据。用户在浏览器中看到的实时数据并非直接嵌入在初始HTML中,而是通过JavaScript在页面加载后向后端API发起请求,并将返回的数据渲染到页面上。
对于Yahoo财经的收益日历页面,直接解析其HTML (https://finance.yahoo.com/calendar/earnings?day={date}) 往往只能获取到页面的静态骨架,而实际的收益数据(如公司名称、收益发布时间等)则是由JavaScript异步加载的。因此,传统的requests + BeautifulSoup组合无法直接获取到这些动态数据。
要成功抓取动态加载的数据,我们需要模拟浏览器发起的实际API请求。这通常涉及以下步骤:
通过对Yahoo财经收益日历页面的分析,可以发现其动态数据是通过向 https://query2.finance.yahoo.com/v1/finance/visualization 这个API端点发送 POST 请求获取的。
立即学习“Python免费学习笔记(深入)”;
模拟Yahoo财经API请求需要以下几个关键组成部分:
User-Agent 是一个重要的请求头,它告诉服务器发起请求的客户端类型。模拟一个常见的浏览器User-Agent可以有效避免某些网站的简单反爬机制。
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
}URL中包含一些查询参数,这些参数通常用于指定语言、地区等信息。crumb 参数是一个安全令牌,它可能会随时间变化。在实际生产环境中,可能需要先从页面动态获取此crumb值。
params = {
"crumb": "EwuCwsPbKM2", # 此值可能需要动态获取
"lang": "en-US",
"region": "US",
"corsDomain": "finance.yahoo.com",
}这是最核心的部分,它定义了要查询的数据类型、字段、过滤条件(如日期范围、地区)和排序方式。
query = {
"entityIdType": "earnings",
"includeFields": [
"ticker",
"companyshortname",
"eventname",
"startdatetime",
"startdatetimetype",
"epsestimate",
"epsactual",
"epssurprisepct",
"timeZoneShortName",
"gmtOffsetMilliSeconds",
],
"offset": 0,
"query": {
"operands": [
{"operands": ["startdatetime", "2023-12-15"], "operator": "gte"}, # 查询开始日期
{"operands": ["startdatetime", "2023-12-16"], "operator": "lt"}, # 查询结束日期 (不包含)
{"operands": ["region", "us"], "operator": "eq"},
],
"operator": "and",
},
"size": 100,
"sortField": "companyshortname",
"sortType": "ASC",
}A3 cookie是另一个重要的组成部分,它可能与用户会话或认证有关。与crumb类似,这个cookie的值也可能动态变化,需要特别注意。在提供的示例中,它被硬编码,但在实际应用中,更稳健的方法是在每次请求前获取最新的A3 cookie。
# 此cookie值可能随时间变化,需要定期更新或动态获取 cookie = "d=AQABBK8KXmQCEA8-VE0dBLqG5QEpQ7OglmEFEgABCAHCeWWpZfNtb2UB9qMAAAcIqgpeZJj7vK8&S=AQAAAqhyTAOrxcxONc4ktfzCOkg"
结合以上分析,我们可以构建一个完整的Python脚本来抓取指定日期的Yahoo财经收益数据。
import requests
from datetime import date, timedelta
def get_yahoo_earnings(target_date: date):
"""
从Yahoo财经API获取指定日期的收益数据。
Args:
target_date (date): 要查询的日期对象。
Returns:
list: 包含收益数据字典的列表,如果请求失败则返回空列表。
"""
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
}
url = "https://query2.finance.yahoo.com/v1/finance/visualization"
# crumb参数可能需要动态获取,此处为示例值
params = {
"crumb": "EwuCwsPbKM2", # 注意:此值可能失效,需要从Yahoo页面动态抓取
"lang": "en-US",
"region": "US",
"corsDomain": "finance.yahoo.com",
}
# 构建查询日期范围
start_date_str = target_date.strftime("%Y-%m-%d")
end_date_str = (target_date + timedelta(days=1)).strftime("%Y-%m-%d")
query = {
"entityIdType": "earnings",
"includeFields": [
"ticker",
"companyshortname",
"eventname",
"startdatetime",
"startdatetimetype",
"epsestimate",
"epsactual",
"epssurprisepct",
"timeZoneShortName",
"gmtOffsetMilliSeconds",
],
"offset": 0,
"query": {
"operands": [
{"operands": ["startdatetime", start_date_str], "operator": "gte"},
{"operands": ["startdatetime", end_date_str], "operator": "lt"},
{"operands": ["region", "us"], "operator": "eq"},
],
"operator": "and",
},
"size": 100, # 可根据需要调整每页返回数量
"sortField": "companyshortname",
"sortType": "ASC",
}
# A3 cookie也可能失效,需要动态获取
cookie = "d=AQABBK8KXmQCEA8-VE0dBLqG5QEpQ7OglmEFEgABCAHCeWWpZfNtb2UB9qMAAAcIqgpeZJj7vK8&S=AQAAAqhyTAOrxcxONc4ktfzCOkg"
earnings_data = []
with requests.Session() as s:
s.headers.update(headers)
s.cookies["A3"] = cookie # 设置A3 cookie
try:
response = s.post(url, params=params, json=query)
response.raise_for_status() # 检查HTTP错误
data = response.json()
if data and "finance" in data and "result" in data["finance"] and \
data["finance"]["result"] and data["finance"]["result"][0]["documents"]:
for doc in data["finance"]["result"][0]["documents"]:
if "rows" in doc:
for r in doc["rows"]:
# 提取并格式化数据
company_name = r[1] if len(r) > 1 else ""
event_name = r[2] if len(r) > 2 and r[2] else ""
start_datetime = r[3] if len(r) > 3 else ""
earnings_data.append({
"company_name": company_name,
"event_name": event_name,
"start_datetime": start_datetime
})
else:
print(f"API响应中未找到预期数据结构: {data}")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
except ValueError as e:
print(f"JSON解析错误: {e}")
return earnings_data
if __name__ == "__main__":
# 获取昨天的日期 (假设今天是周日,昨天是周六,我们需要周五的收益)
# 实际应用中,可以直接指定日期
today = date.today()
# 调整为上一个工作日,例如,如果今天是周日,则获取上周五的日期
target_date = today - timedelta(days=2) # 示例:如果今天是周日,这将是周五
print(f"尝试获取 {target_date.strftime('%Y-%m-%d')} 的收益数据...")
earnings = get_yahoo_earnings(target_date)
if earnings:
print(f"\n{target_date.strftime('%Y-%m-%d')} 收益数据:")
for item in earnings:
print(f"{item['company_name']:<40} {item['event_name']:<40} {item['start_datetime']:<30}")
else:
print(f"未能获取 {target_date.strftime('%Y-%m-%d')} 的收益数据。")
# 示例:获取特定日期的收益
specific_date = date(2023, 12, 15)
print(f"\n尝试获取 {specific_date.strftime('%Y-%m-%d')} 的收益数据...")
earnings_specific = get_yahoo_earnings(specific_date)
if earnings_specific:
print(f"\n{specific_date.strftime('%Y-%m-%d')} 收益数据:")
for item in earnings_specific:
print(f"{item['company_name']:<40} {item['event_name']:<40} {item['start_datetime']:<30}")
else:
print(f"未能获取 {specific_date.strftime('%Y-%m-%d')} 的收益数据。")示例输出 (根据实际API响应可能有所不同):
尝试获取 2023-12-15 的收益数据... 2023-12-15 收益数据: Lewis and Clark Bank Q3 2023 Earnings Release 2023-12-15T13:10:00.000Z Alzamend Neuro, Inc. 2023-12-15T16:32:00.000Z ATIF Holdings Ltd Q1 2024 Earnings Release 2023-12-15T21:00:00.000Z Barnwell Industries Inc Q4 2023 Earnings Release 2023-12-15T23:05:13.000Z Quanex Building Products Corp Q4 2023 Earnings Call 2023-12-15T16:00:00.000Z PharmaCyte Biotech, Inc. 2023-12-15T17:27:00.000Z Edesa Biotech, Inc. 2023-12-15T16:10:00.000Z Butler National Corporation 2023-12-15T09:47:00.000Z Enzo Biochem, Inc. 2023-12-15T16:17:00:00.000Z Everything Blockchain Inc Q3 2024 Earnings Release 2023-12-15T21:05:00.000Z ... (更多数据)
通过模拟Yahoo财经的后端API请求,我们可以有效地绕过前端JavaScript渲染的限制,直接获取结构化的动态数据。这种方法比传统的BeautifulSoup解析更稳定、更高效,并且能够获取更精确的数据。然而,动态参数(如crumb和cookie)的管理是实现健壮爬虫的关键挑战,需要开发者投入额外精力进行动态获取和维护。遵循上述最佳实践,可以帮助您构建一个稳定且高效的Yahoo财经收益数据爬虫。
以上就是使用Python爬取Yahoo财经动态收益数据教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号