python的urlopen失败的原因

617次阅读
没有评论

python的urlopen失败的原因

在使用python3中的urllib.request模块抓取网页的时候使用一下的代码会报一个urllib.error.URLError错误

import urllib.request
response = urllib.request.urlopen('https://www.python.org')
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to
 get local 
issuer certificate (_ssl.c:1045)>

这个错误是因为Python 2.7.9 之后引入了一个新特性,当你使用urllib.urlopen一个 https 的时候会验证一次 SSL证书。当目标使用的是自签名的证书时就会报urllib.error.URLError错误。解决方法如下:

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'))

通过导入ssl模块把证书验证改成不用验证就行了。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-09发表,共计664字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)