Urlopen与requests.get无法通过企业代理请求问题求助
企业代理下Python请求的问题排查与解决方向
问题描述
我正在测试通过企业代理发送请求,但遇到urlopen和requests无法识别代码内设置代理的问题:
1. urllib.request代理不生效
使用以下代码时会因连接超时失败,只有在运行Python前执行export https_proxy="https://myproxy:000"才能成功,代码内设置的代理完全无效:
import urllib import ssl prox = urllib.request.getproxies() authinfo = urllib.request.HTTPBasicAuthHandler() proxy_support = urllib.request.ProxyHandler({"https" : "https://myproxy:000"}) opener = urllib.request.build_opener(proxy_support, authinfo, urllib.request.CacheFTPHandler) urllib.request.install_opener(opener) f = urllib.request.urlopen('https://www.google.com/', context=ssl._create_unverified_context()) print(prox) print(f)
2. requests出现SSL错误
使用requests时抛出urllib3.exceptions.SSLError: EOF occurred in violation of protocol (_ssl.c:1131)错误,即使执行上述export命令也无法解决:
import requests proxies = { 'https': 'https://myproxy:000' } r = requests.get('https://google.com/', proxies=proxies, verify=False) print(r)
已尝试的解决方案
- 安装
ndg-httpsclient、pyasn1和pyOpenSSL模块 - 检查TLS版本,当前为1.3
已安装的Python包列表
Authlib 1.2.1 certifi 2023.7.22 cffi 1.15.1 charset-normalizer 3.2.0 cryptography 37.0.4 idna 3.4 ndg-httpsclient 0.5.1 pip 21.3.1 pyasn1 0.5.0 pycparser 2.21 pyOpenSSL 22.0.0 requests 2.31.0 semantic-version 2.10.0 setuptools 68.1.2 setuptools-rust 1.6.0 tornado 6.3.3 typing_extensions 4.7.1 urllib3 2.0.4 wheel 0.41.2
解决方向建议
针对urllib.request代理不生效
- 检查代理地址格式:确认
https://myproxy:000中的端口是否正确,企业代理通常使用8080、3128等端口,替换占位符为真实端口 - 补全代理认证:如果企业代理需要账号密码,当前代码的
HTTPBasicAuthHandler未配置认证信息,需补充:authinfo = urllib.request.HTTPBasicAuthHandler() authinfo.add_password(realm='ProxyRealm', uri='https://myproxy:000', user='你的账号', passwd='你的密码') - 清空环境代理冲突:
getproxies()会读取系统环境变量的代理,若环境中已有设置可能覆盖代码配置,可在代码开头清空:import os os.environ.pop('https_proxy', None) os.environ.pop('http_proxy', None)
针对requests的SSL错误
- 降级urllib3版本:当前使用urllib3 2.0.4,部分企业代理对新TLS握手逻辑兼容不佳,尝试降级到1.26.x版本:
pip install urllib3==1.26.16 - 指定TLS版本:强制使用TLS 1.2(部分企业代理对TLS 1.3支持不完善),通过修改适配器实现:
import requests from requests.adapters import HTTPAdapter from urllib3.poolmanager import PoolManager import ssl class TLS12Adapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1_2 ) proxies = { 'https': 'https://myproxy:000' } session = requests.Session() session.mount('https://', TLS12Adapter()) r = session.get('https://google.com/', proxies=proxies, verify=False) print(r) - 检查代理SSL证书:即使设置
verify=False,部分代理的证书链问题仍可能导致EOF错误,可尝试将代理证书添加到信任列表,或通过REQUESTS_CA_BUNDLE环境变量指定证书路径。
内容的提问来源于stack exchange,提问作者jakebake
相关产品推荐
相关产品推荐

