使用request-html爬取动态页面时如何指定时间范围获取历史赛事数据
解决方案
首先明确:可以通过requests-html修改查询日期获取全量历史赛事数据,你当前代码运行异常的核心原因是请求参数不全、存在多余操作,按以下步骤修正即可:
问题排查与修正要点
- 你调用的接口要求传入的参数不止
start_date,返回提示Please select the gender, league & age of the matches you are looking for已经说明缺少性别、联赛ID、年龄组等必填参数。你需要打开浏览器开发者工具的「网络」面板,手动切换一次日期,找到对应get_matches请求的Form Data部分,复制所有发送的参数,补全到你的POST请求data字段中。 - 不需要调用
response.html.render(),该接口返回的是结构化数据或者纯HTML片段,没有需要渲染的动态内容,调用render反而会提取到页面内嵌的JS脚本,干扰结果解析。 - 需要补充请求头,尤其是
User-Agent和Referer,模拟正常浏览器请求,避免被服务端拦截。如果仍请求失败,可以先访问一次公开赛程页面让会话自动带上有效Cookie,再发送POST请求。
修正后代码示例
from requests_html import HTMLSession session = HTMLSession() # 先访问目标页面获取有效Cookie session.get("https://www.modular11.com/schedule?year=14", headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" }) # POST请求头 post_headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Referer": "https://www.modular11.com/schedule?year=14", "X-Requested-With": "XMLHttpRequest" } # 补全所有从开发者工具中获取的必填参数 post_data = { "start_date": "2021-10-30 00:00:00", "league_id": "从浏览器实际请求中复制对应值", "age_group": "u16", "gender": "对应赛事的性别参数", "year": "14" } url = "https://www.modular11.com/public_schedule/league/get_matches" response = session.post(url, data=post_data, headers=post_headers) if response.status_code == 200: # 接口返回JSON格式直接解析 match_data = response.json() print(match_data) # 若返回HTML片段则用xpath/css选择器提取赛事信息即可 # match_items = response.html.find(".match-item")
内容的提问来源于stack exchange,提问作者Jia Gao
相关产品推荐
相关产品推荐

