2010-05-28 39 views
9

精细这项工作:的Python的urllib2> HTTP代理> HTTPS请求

import urllib2 

opener = urllib2.build_opener(
       urllib2.HTTPHandler(), 
       urllib2.HTTPSHandler(), 
       urllib2.ProxyHandler({'http': 'http://user:[email protected]:3128'})) 
urllib2.install_opener(opener) 
print urllib2.urlopen('http://www.google.com').read() 

但是,如果HTTP变化HTTPS

... 
print urllib2.urlopen('https://www.google.com').read() 

有错误:

Traceback (most recent call last): 
    File "D:\Temp\6\tmp.py", line 13, in <module> 
    print urllib2.urlopen('https://www.google.com').read() 
    File "C:\Python26\lib\urllib2.py", line 124, in urlopen 
    return _opener.open(url, data, timeout) 
    File "C:\Python26\lib\urllib2.py", line 389, in open 
    response = self._open(req, data) 
    File "C:\Python26\lib\urllib2.py", line 407, in _open 
    '_open', req) 
    File "C:\Python26\lib\urllib2.py", line 367, in _call_chain 
    result = func(*args) 
    File "C:\Python26\lib\urllib2.py", line 1154, in https_open 
    return self.do_open(httplib.HTTPSConnection, req) 
    File "C:\Python26\lib\urllib2.py", line 1121, in do_open 
    raise URLError(err) 
URLError: <urlopen error [Errno 10060] 

为什么,以及如何解决这个问题?

+3

如果你正在阅读本:请将正确答案标为正确。这是为了确保没有人浪费时间试图回答已经回答的问题。这也是一种很好的方式来表示感谢为您的问题提出了解决方案的人 – Sheena 2013-02-11 07:08:41

回答

1

在Windows上,errno 10060是一个winsock错误,意味着连接超时。您是否可以使用代理服务器设置为http://user:[email protected]:3128的网络浏览器从同一台机器到达https://www.google.com?你确定你的代理服务器可以在同一个端口上同时处理https和http吗?

16

改变这一行:

urllib2.ProxyHandler({'http': 'http://user:[email protected]:3128'})) 

这样:

urllib2.ProxyHandler({'https': 'http://user:[email protected]:3128'})) 

它工作正常的我。

+0

是的,这是正确的解决方案 – fijiaaron 2012-01-24 16:32:30

+0

urllib2.ProxyHandler({'https':'https:// user:pass @ proxy: 3128'})) 如果您想在urllib2中同时使用http和http代理,请将第二个http更改为https – k9b 2016-03-01 08:07:26

1

documentation为urllib2的说以下内容:

注意:目前的urllib2不通过代理支持HTTPS位置 抓取。然而,这可以通过将作为this recipe中显示的urllib2来启用。

我必须承认上面的配方没有马上为Jython 2.5.3工作,但我仍然在尝试。

UPDATE:我向Jython 2.5.3申请了this patch,它对我很有用。我现在可以通过代理服务器获取HTTPS资源。

UPDATE2:这里是代码查询使用HTTPS通过HTTP代理服务器的基本身份验证资源(不要忘了安装补丁FIRST(见以前的更新)):

from suds.client import Client 
from suds.transport.https import HttpAuthenticated 

credentials = dict(username='...', password='...', proxy={'https': 'host:port', 'http': 'host:port'}) 
t = HttpAuthenticated(**credentials) 
url = 'https://example.com/service?wsdl' 
client = Client(url, transport=t) 
print client.service.getFoo()