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

JupyterLite环境下爬取Pro-Football-Reference网站的请求头配置问题

JupyterLite环境下爬取Pro-Football-Reference网站的请求头配置问题

Hey Raul, 我来帮你搞定JupyterLite里爬取Pro-Football-Reference的问题!

首先得说清楚,你遇到的ConnectionError不全是请求头的锅——JupyterLite运行在浏览器沙箱里,受**同源策略(CORS)**限制,直接用requests库发起跨域请求很容易被浏览器拦截,这是核心问题之一。另外你的代码里最后调用了.json(),但目标页面返回的是HTML,不是JSON数据,这也会触发解析错误哦。

接下来给你分步解决:

一、补充完善请求头

除了User-Agent,你还可以添加这些字段,让请求更贴近真实浏览器的行为,降低被反爬拦截的概率:

  • Accept: 告诉服务器你能接受的内容类型
  • Accept-Language: 指定语言偏好
  • Referer: 模拟从网站首页跳转过来的请求
  • DNT: 表明你不希望被追踪
  • Connection和Upgrade-Insecure-Requests: 保持连接并请求HTTPS资源

二、改用Pyodide的专用请求方法

在JupyterLite里,requests库的底层是浏览器的XMLHttpRequest,受CORS限制很难绕过。推荐用Pyodide官方提供的pyodide.http.open_url,它能适配浏览器环境,处理跨域请求。

修正后的完整代码

import pandas as pd
from pyodide.http import open_url

# 配置更完整的请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Referer': 'https://www.pro-football-reference.com/',
    'DNT': '1',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1'
}

team_stats_url = 'https://www.pro-football-reference.com/years/2022/'

try:
    # 使用open_url发起请求,避免CORS限制
    with open_url(team_stats_url, headers=headers) as response:
        html_content = response.read().decode('utf-8')
    
    # 用pandas直接提取页面中的表格(Pro-Football-Reference的表格结构很适合用read_html)
    df_list = pd.read_html(html_content)
    # 第一个表格通常是年度球队统计数据,你可以根据需求调整索引
    team_stats_df = df_list[0]
    print(team_stats_df.head())
except Exception as e:
    print(f"请求失败:{str(e)}")

额外提醒

  • 网站可能有反爬机制,频繁请求容易被封IP,建议不要短时间内重复请求,必要时可以添加请求延迟(比如用time.sleep())。
  • 如果后续需要解析更复杂的页面内容,你可以结合BeautifulSoup库来处理HTML,在JupyterLite里直接用pip install beautifulsoup4安装即可。

备注:内容来源于stack exchange,提问作者Raul Ojeda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:48:03