使用Python requests调用无文档API遇HTTP 403错误,浏览器访问正常
调用无官方支持API时Python请求403但浏览器正常的问题排查与解决
问题描述
调用某无官方文档、不被官方支持的API时遇到异常:API链接在各类浏览器中均可正常访问(Chrome返回200 OK),但通过Python脚本发起请求时始终返回HTTP 403错误。
已排除的可能性
- 认证/Cookie/会话数据问题:多款浏览器删除Cookie、退出账号后仍能正常访问该API
- IP封禁或速率限制:仅发送单个请求,同一IP下浏览器访问完全正常
尝试过的无效方案
曾猜测是User-Agent请求头问题,尝试将Python脚本中的User-Agent及其他请求头完全匹配Chrome的配置,但依然无效;全网搜索相关问题后未找到可行解决方案。
所用Python脚本
import requests, json data = "data" headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache', 'Cookie': '__cflb=02DiuFQAkRrzD1P1mdkJhfdTc9AmTWwYjJGtpDcTftSd2; X-Mapping-Server=s7; cf_clearance=I2RZ8gC2GNXzVT0nf_bcKUQEtU5oGRrFq6Eq1OjR_Xs-1696873939-0-1-5622ec48.635f2445.c3629c20-0.2.1696873939', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36' } # API endpoint endpoint = f"http://link-to-api/{data}/" # Send an HTTP GET request to the API endpoint response = requests.get(endpoint, headers=headers) if response.status_code == 200: data = response.json() print(f"Response code: {response.status_code}") print(data) else: print(f"{response.status_code} Error: {response.reason}")
注:已修正脚本中端点定义的引号缺失、请求参数名不匹配的语法错误
输出情况
- 预期输出:打印API返回的JSON数据
- 实际输出:
403 Error: Forbidden
问题原因与解决方案
问题原因
经过逆向分析该API及调研后确认,目标API采用了TLS JA3指纹验证。requests库使用的TLS握手指纹与浏览器存在差异,被服务器识别为非浏览器请求,从而返回403 Forbidden。
解决方案
使用curl_cffi Python模块模拟Chrome的JA3指纹发起请求,即可绕过该验证。示例代码如下:
from curl_cffi import requests data = "data" endpoint = f"http://link-to-api/{data}/" # 模拟Chrome浏览器的请求 response = requests.get(endpoint, impersonate="chrome117") if response.status_code == 200: print(f"Response code: {response.status_code}") print(response.json()) else: print(f"{response.status_code} Error: {response.reason}")
内容的提问来源于stack exchange,提问作者Pyro
相关产品推荐
相关产品推荐

