urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)

Error Reproduce:
python3执行如下代码:
import urllib.request
response = urllib.request.urlopen(‘https://www.python.org’)
print(response.read().decode(‘utf-8’))
结果报错如下:
Exception has occurred: urllib.error.URLError

File “/Volumes/IMACII/Python/CQCscrap/urlopen.py”, line 2, in
response = urllib.request.urlopen(‘https://www.python.org’)

Analysis:
在Python 2.7.9 之后版本引入了一个新特性:urllib.urlopen一个 https 的时会验证SSL 证书,当目标使用的是自签名证书时便报错如下:
urllib.URLError: 的错误消息,
Solution:
引入ssl lib,并将ssl defatult设置为unverified具体如下:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

Summary:
按照如下方式执行成功:
import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
response = urllib.request.urlopen(‘https://www.python.org’)
print(response.read().decode(‘utf-8’))

Reference:
https://www.zhaokeli.com/Article/6341.html

你可能感兴趣的:(urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833))