【发布时间】:2015-07-02 05:51:18
【问题描述】:
所以我正在尝试使用 python 2.7 来做各种需要从互联网上提取数据的事情。我不是很成功,我正在寻求帮助来诊断我做错了什么。
首先,我通过像 pip install --proxy=http://username:password@someproxy.com:8080 numpy 这样定义代理来设法让 pip 工作。 因此python必须能够通过它!
然而,当我真正编写一个可以做同样事情的 .py 脚本时,我没有成功。我首先尝试将以下代码与 urllib2 一起使用:
import urllib2
uri = "http://www.python.org"
http_proxy_server = "someproxyserver.com"
http_proxy_port = "8080"
http_proxy_realm = http_proxy_server
http_proxy_user = "username"
http_proxy_passwd = "password"
# Next line = "http://username:password@someproxyserver.com:8080"
http_proxy_full_auth_string = "http://%s:%s@%s:%s" % (http_proxy_user,
http_proxy_passwd,
http_proxy_server,
http_proxy_port)
def open_url_no_proxy():
urllib2.urlopen(uri)
print "Apparent success without proxy server!"
def open_url_installed_opener():
proxy_handler = urllib2.ProxyHandler({"http": http_proxy_full_auth_string})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
urllib2.urlopen(uri)
print "Apparent success through proxy server!"
if __name__ == "__main__":
open_url_no_proxy()
open_url_installed_opener()
但是我只是得到这个错误:
URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
然后我尝试了 urllib3,因为这是 pip 用来处理代理的模块:
from urllib3 import ProxyManager, make_headers
# Establish the Authentication Settings
default_headers = make_headers(basic_auth='username:password')
http = ProxyManager("https://www.proxy.com:8080/", headers=default_headers)
# Now you can use `http` as you would a normal PoolManager
r = http.request('GET', 'https://www.python.org/')
# Check data is from destination
print(r.data)
我收到了这个错误:
raise MaxRetryError(_pool, url, error or ResponseError(cause)) MaxRetryError: HTTPSConnectionPool(host='www.python.org', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authorization Required',)))
我非常感谢诊断此问题的任何帮助。
【问题讨论】:
-
您的代理是在 https:// 还是 http://?在 pip 示例中是 http://,但 urllib3 示例中是 https://。
-
如果这不起作用,您可以尝试使用 Requests(基于 urllib3,也由 pip 使用):docs.python-requests.org/en/latest/user/advanced/…
-
是的,我玩过 http 与 https,实际上,当我使用 urllib3 将其设置为 http 时,它没有任何错误,但是它返回一个页面,告诉我代理需要身份验证.
-
我尝试了一个带有请求的脚本,但我遇到了类似的错误。我开始认为它与提供它的身份验证细节有关。
-
可能是。奇怪的是 pip 有效。您确定 pip 实际上是在命中代理而不是以某种方式忽略它吗?您可以使用 tcpdump/ngrep 之类的东西来监控流量并查看它实际在做什么。例如。 stackoverflow.com/questions/9241391/…
标签: python-2.7 proxy urllib2 urllib3