问题描述:
当使用 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)
- …
问题原因:
造成此错误的原因可能有多种,以下是一些可能的原因:
- 代理服务器出现故障导致无法连接。
- 提供的代理地址不正确。
- 代理服务器的连接数已满,无法再建立新的连接。
- 网络故障导致连接被重置或超时,如 firewalls、防火墙、路由器等问题。
- SSL 证书问题,如目标网站使用了自签名证书或证书验证失败等情况。
- …
解决办法攻略:
针对以上可能的原因,我们可以采取以下方案进行解决:
- 尝试切换代理或等待代理服务器故障排除。
- 检查代理地址是否正确。
- 等待代理服务器空闲或咨询代理提供商关于代理连接数的限制。
- 检查网络故障,如防火墙等设备的设置、网络连接稳定性等。
- 尝试禁用 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 请求库。