对于Python和Requests / Urllib2库,我认为自己是一名高级开发人员。
我最近使用Parallels切换到运行OSX和Win10的Mac。 在使用它的代理选择方法运行上述任何一个库时,OSX忽略自定义http请求代理设置并继续使用我的公共IP,如果我使用Win10,则不会发生这种情况。
方法尝试:
def simple_request(self):
base_url = "www.whatever.com"
proxy = "http://192.168.2.1:8080"
# i am using jsonip.com as a host to get my request IP
r = requests.get(r'http://jsonip.com', proxies={"http": proxy})
ip = r.json()['ip'] # will always be my public ip
我一直在使用以两种方式测试有效的代理:
使用Win10 python脚本应用相同的方法。
将相同的代理设置应用于OSX Networks首选项管理器。
此外,即使使用无效代理,我也永远不会收到以下错误:
requests.exceptions.ConnectionError: HTTPConnectionPool Max retries exceeded with url
当我将无效的代理设置应用于OSX Networks首选项管理器时,我确实收到此错误。
我尝试在osx下使用代理,同时提到了两个库,我得到了相同的结果。
尝试了其他解决方案:
使用Requests.Session管理器在发送请求之前使用代理构建请求。
使用以下https://stackoverflow.com/a/39934154/4255373 - 它 将更改我的设置,但我必须重新启动我的代码才能使用它, 并且不将连接设置更改为整个OS服务 对我来说是一个有效的解决方案。
有什么建议吗?
感谢。
更新: 使用日志记录模块,我得到以下内容:
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): 199.116.113.206
send: 'GET http://jsonip.com/ HTTP/1.1\r\nHost: jsonip.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.11.1\r\n\r\n'
reply: 'HTTP/1.1 301 Moved Permanently\r\n'
header: Date: Thu, 12 Jan 2017 02:13:25 GMT
header: Server: nginx/1.10.0 (Ubuntu)
header: Content-Type: text/html
header: Content-Length: 194
header: Location: https://jsonip.com/
header: Keep-Alive: timeout=5, max=100
header: Connection: Keep-Alive
DEBUG:requests.packages.urllib3.connectionpool:"GET http://jsonip.com/ HTTP/1.1" 301 194
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): jsonip.com
send: 'GET / HTTP/1.1\r\nHost: jsonip.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.11.1\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Server: nginx/1.10.0 (Ubuntu)
header: Date: Thu, 12 Jan 2017 02:13:25 GMT
header: Content-Type: application/json; charset=utf-8
header: Transfer-Encoding: chunked
header: Connection: keep-alive
header: Access-Control-Allow-Origin: *
header: Access-Control-Allow-Methods: GET
header: Strict-Transport-Security: max-age=31536000;
DEBUG:requests.packages.urllib3.connectionpool:"GET / HTTP/1.1" 200 None
答案 0 :(得分:1)
好的菜鸟错误。
我已经按照 l' L' l 建议 - 简单但重要 - 并且在将所有urllib3连接记录到控制台后我意识到 我试图使用HTTP代理连接到HTTPS服务器,因此失败了。
我仍然不明白为什么在没有打印到控制台的异常或警告的情况下自动忽略代理,以及为什么连接管理器在没有代理的情况下继续发送请求。