Python 3.11与3.10间requests库请求403异常求助
解决Python 3.11下investpy请求返回403的问题
核心原因
Python 3.11与3.10在requests底层依赖(如urllib3、SSL库)的默认行为存在差异,导致目标服务器识别请求为异常,返回403 Forbidden,即便使用相同版本的requests库。
具体解决方案
对比请求头差异
在两个Python版本中,打印完整请求头找出区别:import requests url = "目标请求URL" headers = {"User-Agent": "你的固定UA"} req = requests.Request('GET', url, headers=headers) prepared = req.prepare() print(prepared.headers)重点检查是否存在
Sec-Fetch-*、Accept-Encoding等新增或值不同的头字段,这些可能是服务器拦截的关键。强制兼容TLS握手行为
Python 3.11默认的TLS安全级别或握手方式可能不被目标服务器支持,通过自定义适配器调整:import requests from requests.adapters import HTTPAdapter from urllib3.util.ssl_ import create_urllib3_context class TLSCompatAdapter(HTTPAdapter): def init_poolmanager(self, *args, **kwargs): ctx = create_urllib3_context() # 降低安全级别以兼容旧服务器 ctx.set_ciphers('DEFAULT@SECLEVEL=1') # 启用旧版服务器连接模式 ctx.options |= 0x4 # OP_LEGACY_SERVER_CONNECT kwargs['ssl_context'] = ctx super().init_poolmanager(*args, **kwargs) # 使用自定义适配器的Session发送请求 session = requests.Session() session.mount('https://', TLSCompatAdapter()) response = session.get(url, headers=headers)完全对齐Python 3.10的请求头
将3.10中打印出的所有请求头(除Host外)手动复制到3.11的请求中,确保请求特征完全一致:headers = { 'User-Agent': '你的固定UA', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', # 其他从3.10获取的头字段 } response = requests.get(url, headers=headers)移除自动添加的可疑头字段
Python 3.11的requests可能自动添加Sec-Fetch-User、Sec-Fetch-Mode等现代浏览器头,服务器可能识别为非浏览器请求,手动删除这些字段:session = requests.Session() # 删除自动添加的可疑头 for header in ['Sec-Fetch-User', 'Sec-Fetch-Mode', 'Sec-Fetch-Site']: if header in session.headers: del session.headers[header] response = session.get(url, headers=headers)
内容的提问来源于stack exchange,提问作者dj_tech
相关产品推荐
相关产品推荐

