我熟悉将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>
我尝试了@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
模块。
对于一个请求,只需执行:
requests
对于多个请求,请使用import requests
r = requests.get("http://www.google.com",
proxies={"http": "http://61.233.25.166:80"})
print(r.text)
对象,因此您不必在所有请求中都添加Session
参数:
proxies
我建议您只使用请求模块。
比内置的http客户端要容易得多: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://docs.python-requests.org/en/latest/index.html
[只想提一下,在需要访问https URL的情况下,您可能还必须设置r = requests.get('http://www.thepage.com', proxies={"http":"http://myproxy:3129"})
thedata = r.content
OS环境变量。就我而言,这对我来说并不明显,我花了好几个小时才发现。
我的用例:Win 7,jython-standalone-2.5.3.jar,通过ez_setup.py安装setuptools
Python 3:
https_proxy
我在jython客户端上遇到此问题。服务器仅使用TLS,客户端使用SSL上下文。
import urllib.request
htmlsource = urllib.request.FancyURLopener({"http":"http://127.0.0.1:8080"}).open(url).read().decode("utf-8")
一旦客户端使用TLS,事情就开始起作用。