Requests报”requests.exceptions.TunnelError: {tunnel error message} “的原因以及解决办法

  • Post category:Python

问题描述:

当使用 Requests 库进行 HTTP 请求时,可能会遇到以下错误提示:

requests.exceptions.TunnelError: Could not establish connection to proxy {proxy address}: {tunnel error message} 

错误提示中的 {proxy address} 表示代理地址,{tunnel error message} 表示错误信息。其中 {tunnel error message} 可能有多种情况,如下所示:

  • Max retries exceeded with url
  • [Errno 61] Connection refused
  • [Errno 111] Connection refused
  • [Errno 110] Connection timed out
  • [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)

问题原因:

造成此错误的原因可能有多种,以下是一些可能的原因:

  1. 代理服务器出现故障导致无法连接。
  2. 提供的代理地址不正确。
  3. 代理服务器的连接数已满,无法再建立新的连接。
  4. 网络故障导致连接被重置或超时,如 firewalls、防火墙、路由器等问题。
  5. SSL 证书问题,如目标网站使用了自签名证书或证书验证失败等情况。

解决办法攻略:

针对以上可能的原因,我们可以采取以下方案进行解决:

  1. 尝试切换代理或等待代理服务器故障排除。
  2. 检查代理地址是否正确。
  3. 等待代理服务器空闲或咨询代理提供商关于代理连接数的限制。
  4. 检查网络故障,如防火墙等设备的设置、网络连接稳定性等。
  5. 尝试禁用 SSL 验证或安装证书,如下代码:
import requests
requests.packages.urllib3.disable_warnings()
response = requests.get(url, verify=False)

以上代码会禁用 SSL 验证,在进行 HTTPS 请求时会跳过 SSL 证书验证。如果需要验证证书,则可以将证书添加到 trusted_roots 中:

import requests
response = requests.get(url, verify='/path/to/certificate.pem')

如果问题仍然无法解决,建议更换 Requests 版本或者使用其他的 HTTP 请求库。