You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium获取NFLPickWatch专家预测信息并整理为字典

问题需求

需要抓取nflpickwatch.com上所有专家的预测结果,整理为{"专家姓名": "预测获胜球队"}的字典格式。网站采用JavaScript渲染,因此用Selenium实现;专家信息位于class为row-yellow或row-yellow-dark的<tr>元素下。当前代码仅能获取所有选择的列表,无法关联姓名与对应的预测结果。

修正后的代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

info = {}
website = "https://nflpickwatch.com/nfl/picks/su/experts"
service = Service("C:\Program Files\Mozilla Firefox\geckodriver.exe")
driver = webdriver.Firefox(service=service)
driver.maximize_window()
driver.implicitly_wait(10)
driver.get(website)

# 处理弹窗广告(兼容广告加载延迟或未加载的情况)
try:
    WebDriverWait(driver, 10).until(
        EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe[contains(@class, "intercom")]'))
    )
    close_btn = WebDriverWait(driver, 5).until(
        EC.element_to_be_clickable((By.XPATH, '//span[@aria-label="Close"]'))
    )
    close_btn.click()
    driver.switch_to.default_content()
except:
    # 广告未加载或无法定位时直接跳过
    pass

# 获取所有专家数据行
expert_rows = driver.find_elements(By.XPATH, '//tr[@class="row-yellow" or @class="row-yellow-dark"]')

for row in expert_rows:
    # 提取当前行的专家姓名
    expert_name = row.find_element(By.XPATH, './/td[@class="text-left pl-3"]').text.strip()
    # 提取当前专家的所有预测选择
    picks = row.find_elements(By.XPATH, './/div[@class="rounded transparent-border"]')
    # 将所有预测球队整理为字符串(可根据需求改为单一场次的预测)
    predicted_teams = ", ".join([pick.get_attribute('title') for pick in picks if pick.get_attribute('title')])
    # 存入字典
    info[expert_name] = predicted_teams

# 输出结果
for name, teams in info.items():
    print(f"{name}: {teams}")

driver.close()
关键改动说明
  • 批量获取专家行:将find_element改为find_elements,获取所有专家的数据行,避免仅读取第一行数据。
  • 行内元素精准定位:使用相对路径XPath(以.开头)在当前专家行内查找元素,确保姓名与预测结果一一对应,不会混淆不同专家的数据。
  • 广告处理优化:添加显式等待和异常捕获,避免因广告加载异常导致程序中断。
  • 数据关联存储:遍历每行时直接将专家姓名与对应预测存入字典,实现需求的键值对格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:05:34