Python爬虫页面爬取时遇到SSL错误:UNSAFE_LEGACY_RENEGOTIATION_DISABLED解决方案
错误描述:[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled (_ssl.c:1006)
尝试了很多方法:
1.使用 requests.get(),设置verify=false。
2.使用 urllib3库。
3.调用 cryptography、requests请求数据。
4.创建 openssl.cnf文件。
最终解决方法:
import ssl
import requests
class TLSAdapter(requests.adapters.HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
ctx = ssl.create_default_context()
ctx.set_ciphers("DEFAULT@SECLEVEL=1")
ctx.options |= 0x4 # <-- the key part here, OP_LEGACY_SERVER_CONNECT
kwargs["ssl_context"] = ctx
return super(TLSAdapter, self).init_poolmanager(*args, **kwargs)
url = 'https://www.baidu.com/'
with requests.session() as s:
s.mount("https://", TLSAdapter())
print(s.get(url).content.decode('utf-8'))
可直接复制成一个测试文件执行
参考文档:https://stackoverflow.com/questions/76907660/sslerror-when-accessing-sidra-ibge-api-using-python-ssl-unsafe-legacy-rene
作者:1二山似