【发布时间】:2015-09-30 18:49:29
【问题描述】:
使用 urllib2,最新版本允许在调用 urlopen 时使用可选参数“context”。
我整理了一些代码来使用它:
# For Python 3.0 and later
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen, HTTPError, URLError
import ssl
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
response = urlopen(url=url, context=context)
用我的 python 2.78 运行它...我明白了:
Traceback (most recent call last):
File "test.py", line 5, in <module>
context = ssl.create_default_context()
AttributeError: 'module' object has no attribute 'create_default_context'
所以我想:那就去python3吧;现在我得到了:
Traceback (most recent call last):
File "test.py", line 15, in <module>
response = urlopen(url=url, context=context)
TypeError: urlopen() got an unexpected keyword argument 'context'
我花了一段时间才发现使用该命名参数上下文...还需要比我的 ubuntu 14.04 上安装的 3.4.0 更新的 python 版本。
我的问题:在调用 urlopen 时检查“上下文”是否可以使用的“规范”方法是什么?只需调用它并期待 TypeError?或者对我正在运行的 python 做一个确切的版本检查?
我确实在这里和谷歌搜索过,但也许我只是错过了正确的搜索词......因为我找不到任何有用的东西......
【问题讨论】:
标签: python urllib2 optional-parameters