urllib 不将上下文作为参数

urllib not taking context as a parameter

我正在尝试将 sssl.SSlContext 添加到 urlopen 方法,但不断收到错误消息:

TypeError: urlopen() got an unexpected keyword argument 'context'

我正在使用 python 3 和 urllib。这有一个上下文参数定义 - https://docs.python.org/2/library/urllib.html。所以我不明白为什么会抛出错误。但无论哪种方式,这都是代码:

try:
    # For Python 3.0 and later
    from urllib.request import urlopen, Request
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen, Request
request = Request(url, content, headers)
request.get_method = lambda: method

if sys.version_info[0] == 2 and sys.version_info[1] < 8:
    result = urlopen(request)
else:
    gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    result = urlopen(request, context=gcontext)

谁能解释一下我做错了什么?

根据urllib.request.urlopen documentation

Changed in version 3.4.3: context was added.

参数context 将在Python 3.4.3 中添加。您需要回退到较低版本。


在Python 2.x中,它是在Python 2.7.9中添加的。 (urllib.urlopen, urllib2.urlopen)

您查看的文档有误。 https://docs.python.org/3.0/library/urllib.request.html就是你想要的。您正在使用 Python 2.X 文档。