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

Python调用USTA API爬取数据遇403错误,求解决方案

解决USTA网站爬虫403响应问题

问题背景

尝试用Python爬取USTA网站球员信息时,访问https://www.usta.com/usta/api?type=playerInfo接口收到403禁止响应,但浏览器无需登录即可正常请求该接口。浏览器请求时会携带Hash请求头,当前代码未正确处理请求格式及必要头信息。

核心问题分析

  1. 请求格式错误:代码中直接将字典作为data参数传递,requests默认会按form表单格式编码,但接口要求JSON格式的请求体,即便设置了Content-Type头,仍需明确指定JSON传递方式。
  2. 缺少关键请求头:浏览器请求中的Hash头是服务器验证的必要参数,未携带该头会触发反爬拦截。
  3. 可能缺少Referer头:服务器可能验证请求的来源页面,需添加对应Referer模拟浏览器上下文。

修正方案

  1. 从浏览器开发者工具中复制真实请求的Hash头值,添加到请求头字典中。
  2. 使用json参数传递请求数据,而非data,确保请求体为JSON格式。
  3. 补充Referer头,值为球员页面URL:https://www.usta.com/en/home/play/player-search/profile.html#?uaid=2017185101。

修改后的代码示例

import requests

strURL = "https://www.usta.com/usta/api?type=playerInfo"
dicData = {
    "selection": {"uaid": 2017185101},
    "output": {"ratings": "true", "wtn": "true", "extendedProfile": "true"}
}
dicHead = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
    "Accept": "*/*",
    "Accept-Language": "en-US,en;q=0.5",
    "Content-Type": "application/json; charset=utf-8",
    "Hash": "这里替换为浏览器中真实的Hash头值",
    "Referer": "https://www.usta.com/en/home/play/player-search/profile.html#?uaid=2017185101"
}

# 使用json参数传递数据,自动处理JSON编码
r = requests.post(strURL, json=dicData, headers=dicHead)
print(r.status_code)
print(r.json())  # 如果响应是JSON格式,可直接解析

注意事项

  • Hash头值可能会随时间或会话变化,需每次从浏览器最新请求中获取。
  • 若仍出现403,可检查浏览器请求中的其他头(如Cookie、Origin等),逐步添加到代码中模拟完整请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:13:20