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

使用Python requests模块爬取带日期选择器的动态网页问题

解决方案

1. 核心问题分析

网站接口校验严格,仅携带date参数无法绕过验证,需要保持会话状态并补全关键请求头字段,否则会被返回默认的当前日期数据。

2. 具体解决步骤

  • 用requests.Session()维持会话,先访问主页获取必要的Cookie和会话标识
  • 补全浏览器请求头中的关键字段(如User-Agent、X-Requested-With等),模拟真实用户请求
  • 携带目标日期参数调用API接口

3. 代码实现

import requests

# 初始化会话,保持Cookie和会话状态
session = requests.Session()

# 模拟浏览器请求头,字段可从浏览器网络面板复制
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
    'Referer': 'https://www.lines.com/betting/nba/odds/',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'X-Requested-With': 'XMLHttpRequest',
    'Accept-Language': 'en-US,en;q=0.9'
}

# 先访问主页,建立有效会话
session.get('https://www.lines.com/betting/nba/odds/', headers=headers)

# 目标日期,格式为YYYY-MM-DD
target_date = '2023-01-23'
api_url = f'https://www.lines.com/betting/nba/odds/best-line?date={target_date}'

# 请求目标日期数据
response = session.get(api_url, headers=headers)

# 处理响应内容(假设返回JSON格式,根据实际调整)
if response.status_code == 200:
    odds_data = response.json()
    print(odds_data)
else:
    print(f"请求失败,状态码:{response.status_code}")

4. 额外调试建议

  • 如果仍返回当前日期,复制浏览器网络面板中请求的完整Cookie,添加到headers中测试(注意Cookie有效期)
  • 检查是否存在__csrf_token等隐藏参数,可从主页HTML中提取后加入请求参数或头
  • 确认日期格式严格为YYYY-MM-DD,避免格式错误导致接口忽略参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:55:28