如何使用urllib2通过代理连接到HTTPS(在Python中)

时间:2017-02-12 12:26:58

标签: python-2.7 http https proxy urllib2

如果我尝试通过代理连接的网站是不安全的(HTTP),那么我就能连接,但如果它是安全的(HTTPS),那么我就不能。

以下代码有效:

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>

1 个答案:

答案 0 :(得分:0)

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

  

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

这个允许我连接到使用自签名SSL证书的本地HTTPS站点:

source

我在追溯中注意到与我的相似之处。代码就像你发布的一样,适用于Ubuntu 14.04(Python 2.7.6)但不适用于16.04(Python 2.7.13),但最后一个代码除外:

from bokeh.plotting import figure, curdoc
from bokeh.layouts import column
from bokeh.models import ColumnDataSource

TOOLS = ["tap"]
p = figure(title="Some Figure", tools=TOOLS)

source = ColumnDataSource(dict(
    x=[[1, 3, 2], [3, 4, 6, 6]],
    y=[[2, 1, 4], [4, 7, 8, 5]],
    name=['A', 'B'],color=["firebrick", "navy"],
    alpha=[0.8,0.3],line_width=[3,3]))

pglyph = p.patches('x', 'y', color="color", alpha="alpha",
                   line_width="line_width", source=source)

def callback(attr, old, new):
    # The index of the selected glyph is : new['1d']['indices'][0]
    selections = new['1d']['indices']
    print("Number of selections:{}".format(len(selections)))
    for index in selections:
        patch_name =  source.data['name'][index]
        print("TapTool callback executed on Patch {}".format(patch_name))

pglyph.data_source.on_change('selected',callback)

curdoc().add_root(column(p))

我不确定这是否适用于你。