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

Python requests无法找到表格:MLB三振赔率数据爬取问题

解决Rotowire MLB三振赔率爬取及DataFrame转换问题

原代码存在的问题

  • 错误的URL格式:原代码将Markdown链接语法直接赋值给变量,应该使用纯URL字符串,而非带方括号和括号的格式
  • 缺少请求头:Rotowire会拦截无标识的爬虫请求,需要添加User-Agent模拟浏览器访问
  • 表格索引不确定:pd.read_html返回的表格列表索引不一定是[1],需实际确认目标表格位置
  • 潜在动态内容:部分数据可能通过JavaScript加载,requests无法直接获取完整内容

修正后的解决方案

方案一:静态页面爬取(适用于表格直接渲染的情况)

import requests
import pandas as pd

# 正确的目标URL
url = "https://www.rotowire.com/betting/mlb/player-props.php"

# 添加请求头模拟浏览器访问
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

# 发送请求并检查是否成功
response = requests.get(url, headers=headers)
response.raise_for_status()  # 若请求失败直接抛出异常

# 提取页面中所有表格
tables = pd.read_html(response.text, displayed_only=False)
print(f"共找到 {len(tables)} 个表格")

# 遍历表格,确认哪个是三振赔率数据表格
for idx, table in enumerate(tables):
    print(f"\n=== 表格 {idx} ===")
    print(table.head())

# 找到目标表格后,替换索引进行赋值,比如目标索引为0:
# strikeout_odds_df = tables[0]

方案二:动态页面爬取(适用于JS加载数据的情况)

如果页面数据是通过JavaScript动态渲染的,requests无法获取完整内容,需使用selenium模拟浏览器加载:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pandas as pd

url = "https://www.rotowire.com/betting/mlb/player-props.php"

# 配置Chrome无头模式(后台运行浏览器)
chrome_options = Options()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")

# 启动浏览器并加载页面
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)

# 获取完整页面源码并提取表格
page_source = driver.page_source
tables = pd.read_html(page_source)

# 遍历确认目标表格
for idx, table in enumerate(tables):
    print(f"\n=== 表格 {idx} ===")
    print(table.head())

# 关闭浏览器
driver.quit()

# 赋值目标表格
# strikeout_odds_df = tables[目标索引]

注意事项

  • 网站存在反爬机制,频繁请求可能被IP封禁,建议添加请求间隔(import time; time.sleep(2))
  • 定期检查页面结构,表格索引可能随网站更新发生变化
  • 严格遵守网站的robots.txt规则,避免违规爬取数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:03:08