requests: how to disable / bypass proxy
我正在使用以下网址:
1 | r = requests.get("http://myserver.com") |
正如我在" myserver.com"的" access.log"中看到的那样,使用了客户端的系统代理。 但是我想完全禁用
我目前知道的完全禁用代理的唯一方法是:
- 建立会议
-
将
session.trust_env 设置为False - 使用该会话创建您的请求
1 2 3 4 5 6 | import requests session = requests.Session() session.trust_env = False response = session.get('http://www.stackoverflow.com') |
这是基于Lukasa的评论和
注意:将
-
来自
.netrc 的身份验证信息(代码) -
REQUESTS_CA_BUNDLE 或CURL_CA_BUNDLE (代码)中定义的CA捆绑软件
但是,如果您只想禁用特定域的代理(例如
1 2 3 4 5 6 | import os import requests os.environ['NO_PROXY'] = 'stackoverflow.com' response = requests.get('http://www.stackoverflow.com') |
您可以为每个请求选择代理。从文档:
1 2 3 4 5 6 7 8 | import requests proxies = { "http":"http://10.10.1.10:3128", "https":"http://10.10.1.10:1080", } requests.get("http://example.org", proxies=proxies) |
因此,要禁用代理,只需将每个代理设置为"无":
1 2 3 4 5 6 7 8 | import requests proxies = { "http": None, "https": None, } requests.get("http://example.org", proxies=proxies) |
请求库尊重环境变量。
http://docs.python-requests.org/zh_CN/latest/user/advanced/#proxies
因此,请尝试删除环境变量HTTP_PROXY和HTTPS_PROXY。
1 2 3 4 | import os for k in list(os.environ.keys()): if k.lower().endswith('_proxy'): del os.environ[k] |
阻止请求/ urllib代理任何请求的方法是将
1 | export no_proxy='*' |
或从Python:
1 2 | import os os.environ['no_proxy'] = '*' |
理解为什么这样做是因为urllib.request.getproxies函数首先检查在环境变量中设置的任何代理(例如http_proxy等),或者如果未设置任何代理,则它将使用平台特定的调用(例如在MacOS上)检查系统配置的代理它将使用系统scutil / configd接口进行检查,在Windows上将检查注册表)。
然后,当urllib尝试使用