2017-02-12 159 views
0

如果我試圖通過代理連接到的網站不安全(HTTP),那麼我可以連接,但是如果它是安全的(HTTPS) ,那我就不能。如何使用urllib2通過代理連接到HTTPS(使用Python)

下面的代碼工作:

import urllib2 

proxy_support = urllib2.ProxyHandler({'http':'xxx.xxx.xxx.xx'}) 
opener = urllib2.build_opener(proxy_support) 
urllib2.install_opener(opener) 

html = urllib2.urlopen('http://www.example.com').read() 

但是下面的代碼不能正常工作,

proxy_support = urllib2.ProxyHandler({'https':'xxx.xxx.xxx.xx'}) 
opener = urllib2.build_opener(proxy_support) 
urllib2.install_opener(opener) 

html = urllib2.urlopen('https://www.example.com').read() 

相反,我得到以下回溯:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen 
    return opener.open(url, data, timeout) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open 
    response = self._open(req, data) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open 
    '_open', req) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain 
    result = func(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open 
    context=self._context) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open 
    raise URLError(err) 
urllib2.URLError: <urlopen error [Errno 61] Connection refused> 

回答

0

根據https://docs.python.org/2/library/urllib2.html

版本2.7.9更改:添加了cafile,capath,cadefault和context。

這一次讓我連接到使用自簽名的SSL證書我的本地HTTPS網站:

html = urllib2.urlopen('http://www.example.com'),\ 
context=ssl._https_verify_certificates(False) 

我在你回溯注意到相似之處礦。該代碼,就像你貼出來,工作在Ubuntu 14.04(Python的2.7.6),但在16.04(Python中2.7.13),出現異常的最後一個:

File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen 
    return opener.open(url, data, timeout) 
    File "/usr/lib/python2.7/urllib2.py", line 429, in open 
    response = self._open(req, data) 
    File "/usr/lib/python2.7/urllib2.py", line 447, in _open 
    '_open', req) 
    File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain 
    result = func(*args) 
    File "/usr/lib/python2.7/urllib2.py", line 1241, in https_open 
    context=self._context) 
    File "/usr/lib/python2.7/urllib2.py", line 1198, in do_open 
    raise URLError(err) 
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)> 

我不知道這工作在你的最後。