Python urllib2 > HTTP代理 > HTTPS请求

10

这个可以正常工作:

import urllib2

opener = urllib2.build_opener(
                urllib2.HTTPHandler(),
                urllib2.HTTPSHandler(),
                urllib2.ProxyHandler({'http': 'http://user:pass@proxy: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
3个回答

17

请更改这一行:

urllib2.ProxyHandler({'http': 'http://user:pass@proxy:3128'}))

变为这样:

urllib2.ProxyHandler({'https': 'http://user:pass@proxy:3128'}))

对我来说它运行得很好。


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

1

urllib2的文档中写道:

注意:目前urllib2不支持通过代理获取https位置。但是,可以通过扩展urllib2来启用此功能,如本教程所示。

我必须承认,上述教程对于Jython 2.5.3并没有立即起作用,但我仍在尝试。

更新:我对Jython 2.5.3应用了此补丁,现在它对我起作用了。我现在可以通过代理服务器获取HTTPS资源。

更新2:以下是使用基本身份验证查询HTTP代理的HTTPS资源的代码(请不要忘记先安装补丁(参见上一个更新)):

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()

1

在Windows操作系统中,errno 10060是winsock错误的代表,意味着连接超时。您是否能够使用已设置代理http://user:pass@proxy:3128的Web浏览器从同一台计算机上访问https://www.google.com?您确定您的代理服务器可以在同一端口上处理https和http吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接