我知道应该将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>
任何想法?
即使没有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)
我建议您只使用请求模块。
它比内置的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
只是想提一下,您还可能必须设置 https_proxy
操作系统环境变量,以防需要访问https url。在我的情况下,这对我来说并不明显,我花了几个小时才发现这一点。
我的用例:Win 7, jython-standalone-2.5.3.jar,通过ez_setup.py安装setuptools
Python 3:
import urllib.request
htmlsource = urllib.request.FancyURLopener({"http":"http://127.0.0.1:8080"}).open(url).read().decode("utf-8")
我在jython客户端上遇到了这个问题。服务器只使用TLS,客户端使用SSL上下文。
javax.net.ssl.SSLContext.getInstance("SSL")
一旦客户端连接到TLS,一切就开始工作了