[1330]SSLError(1, '[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy ren

40 阅读1分钟

@[toc]

import requests


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, zstd",
    "accept-language": "zh-CN,zh;q=0.9",
    "connection": "keep-alive",
    "host": "chrm.mohrss.gov.cn",
    "referer": "https://chrm.mohrss.gov.cn/page/1?s=%E6%B2%B9",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}

url = "https://chrm.mohrss.gov.cn/page/1"  # 不能用https,否者报错
params = {
    "s": "油"
}
response = requests.get(url,params= params, headers=headers) # ,verify=False
print(response.status_code)
print(response.text)

报错:

requests.exceptions.SSLError: HTTPSConnectionPool(host='chrm.mohrss.gov.cn', port=443): Max retries exceeded with url: /page/2?s=%E6%B2%B9 (Caused by SSLError(SSLError(1, '[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled (_ssl.c:1007)')))

这个错误发生在 Python 尝试与使用不安全旧版 SSL/TLS 重新协商的服务器建立安全连接时。现代 Python 版本默认禁用了这种不安全的旧版重新协商方式。

解决

# 解决方法1
def demo1():
    url = "http://chrm.mohrss.gov.cn/page/1"  # 不用https,否者报错
    params = {"s": "油"}
    response = requests.get(url,params= params, headers=headers,proxies=proxies) # ,verify=False
    print(response.status_code)
    print(response.text)


# 解决方法2
def demo2():
    import ssl
    import urllib.request

    url = "https://chrm.mohrss.gov.cn/page/1?s=%E6%B2%B9"
    # url = 'http://myip.ipip.net/' # 代理测试

    # Set up SSL context to allow legacy TLS versions
    ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
    ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT

    # 不使用代理 =============================================
    # response = urllib.request.urlopen(url, context=ctx)
    # print(response.status)
    # print(response.read().decode())

    # 使用代理 ===============================================
    # 创建 SSL 上下文(如果需要绕过证书验证)
    # ctx = ssl.create_default_context()
    # ctx.check_hostname = False
    # ctx.verify_mode = ssl.CERT_NONE

    proxy_handler = urllib.request.ProxyHandler(proxies)
    # 创建 opener
    opener = urllib.request.build_opener(
        proxy_handler,
        urllib.request.HTTPSHandler(context=ctx)
    )
    # 只对这次请求使用代理
    response = opener.open(url)
    print(response.read().decode('utf-8'))