You need to enable JavaScript to run this app. Python BeautifulSoup爬取ForexFactory财经日历如何筛选仅USD货币数据
优惠活动
大模型
产品
解决方案
定价
更多

Python BeautifulSoup爬取ForexFactory财经日历如何筛选仅USD货币数据

核心调整方案

只需要在遍历每一条日历行元素的循环中,提前提取该行对应的币种值做判断,非USD的条目直接跳过后续抓取流程即可,完全不需要改动你已经跑通的字段抓取逻辑。

具体修改逻辑

  • 在循环拿到单条日历的<tr>元素后,先定位该条目的币种单元格,取出去除空格的文本值
  • 判断币种值是否为"USD",如果不是直接执行continue跳过本次循环的后续处理,不会进入字段抓取流程
  • 顺手可以优化原代码里的冗余逻辑:把多次调用find_all取第一个元素的写法替换为find,简化原本反复赋值的impact循环,同时把临时字典的变量名从和Python内置类型重名的dict改为更规范的名称

修改后可直接运行的完整代码

table = soup.find_all("tr",{"class":"calendar_row"})
forcal = []
for item in table:
    # 前置提取币种用于过滤
    current_currency = item.find("td", {"class": "calendar__currency"}).text.strip()
    # 非USD条目直接跳过
    if current_currency != "USD":
        continue
    calendar_item = {}
    calendar_item["Currency"] = current_currency
    calendar_item["Event"] = item.find("td",{"class":"calendar__event"}).text.strip()
    calendar_item["Time_Eastern"] = item.find("td", {"class":"calendar__time"}).text.strip()
    # 简化原impact的冗余循环逻辑
    impact_td = item.find("td", {"class": "impact"})
    if impact_td:
        impact_span = impact_td.find("span")
        if impact_span and impact_span.has_attr("title"):
            calendar_item["Impact"] = impact_span["title"].split(' ', 1)[0]
    calendar_item["Actual"] = item.find("td", {"class":"calendar__actual"}).text.strip()
    calendar_item["Forecast"] = item.find("td", {"class":"calendar__forecast"}).text.strip()
    calendar_item["Previous"] = item.find("td", {"class":"calendar__previous"}).text.strip()
    forcal.append(calendar_item)

小提示:

  • 采用前置过滤的方式,比抓完所有字段再统一过滤的性能更好,不会对非USD的条目做无意义的DOM解析
  • 增加了impact节点的存在性判断,碰到部分没有impact标识的条目时不会触发索引报错

内容的提问来源于stack exchange,提问作者Rbutton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.09 17:15:05