使用HTTP代理 - Python
我知道我应该把HTTP_RPOXY这个环境变量设置成代理地址。
一般来说,urllib用起来没问题,但处理urllib2的时候就有点麻烦了。
>>> urllib2.urlopen("http://www.google.com").read()
返回
urllib2.URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
或者
urllib2.URLError: <urlopen error [Errno 11004] getaddrinfo failed>
额外信息:
urllib.urlopen(....)用起来没问题!就是urllib2在搞事情...
我试过@Fenikso的回答,但现在我遇到了这个错误:
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>
有什么想法吗?
5 个回答
6
我想提一下,如果你需要访问https的网址,可能还需要设置一个叫做 https_proxy
的操作系统环境变量。在我的情况下,这一点对我来说并不明显,我花了好几个小时才发现这个问题。
我的使用场景是:Windows 7,使用 jython-standalone-2.5.3.jar,通过 ez_setup.py 安装 setuptools。
19
我建议你直接使用requests模块。
这个模块比Python自带的http客户端简单多了:
http://docs.python-requests.org/en/latest/index.html
下面是一个使用的例子:
r = requests.get('http://www.thepage.com', proxies={"http":"http://myproxy:3129"})
thedata = r.content
73
你甚至可以不使用HTTP_PROXY这个环境变量。试试这个示例:
import urllib2
proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
html = urllib2.urlopen("http://www.google.com").read()
print html
在你的情况下,似乎是代理服务器拒绝了连接。
还有一些其他的尝试:
import urllib2
#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"
proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}
proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)
req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html
编辑于2014年:
这个问题/答案似乎很受欢迎。不过今天我会使用第三方的requests
模块。
如果只是发一个请求,可以这样做:
import requests
r = requests.get("http://www.google.com",
proxies={"http": "http://61.233.25.166:80"})
print(r.text)
如果要发多个请求,可以使用Session
对象,这样就不需要在每个请求中都添加proxies
参数了:
import requests
s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}
r = s.get("http://www.google.com")
print(r.text)