使用HTTP代理 – Python

我很熟悉我应该将HTTP_RPOXY环境variables设置为代理地址。

一般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环境variables,也可以这样做。 试试这个例子:

 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) 

我build议你只使用请求模块。

这比build立在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 URL,您还可能需要设置https_proxy OS环境variables。 在我的情况下,这是不明显的,我试了几个小时才发现这一点。

我的用例: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,事情开始工作。