当前位置:   article > 正文

【Python报错】urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify_line 1344, in do_open h.request(req.get_method(),

line 1344, in do_open h.request(req.get_method(), req.selector, req.data, he

一、问题描述

  笔者是在Anaconda环境下运行python脚本文件遇到了问题,具体报错如下:

Traceback (most recent call last):
  File "D:\Anaconda3\envs\py39\lib\urllib\request.py", line 1342, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "D:\Anaconda3\envs\py39\lib\http\client.py", line 1255, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "D:\Anaconda3\envs\py39\lib\http\client.py", line 1301, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "D:\Anaconda3\envs\py39\lib\http\client.py", line 1250, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "D:\Anaconda3\envs\py39\lib\http\client.py", line 1010, in _send_output
    self.send(msg)
  File "D:\Anaconda3\envs\py39\lib\http\client.py", line 950, in send
    self.connect()
  File "D:\Anaconda3\envs\py39\lib\http\client.py", line 1424, in connect
    self.sock = self._context.wrap_socket(self.sock,
  File "D:\Anaconda3\envs\py39\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "D:\Anaconda3\envs\py39\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "D:\Anaconda3\envs\py39\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

  报错就是因为代码里面默认HTTPS是需要对SSL证书进行验证。因此只要关闭证书验证,代码就能正常运行。

二、解决办法

  在使用urllib.req(est.urlopen()这个代码的文件开头写入如下代码,关闭SSL证书验证。

import ssl
ssl._create_default_https_context = ssl._create_unverified_context
  • 1
  • 2

三、举个例子

  如运行代码如下代码报错

import urllib.request
def main():
	r = urllib.request.urlopen('https://bing.com')
	print(r.status)
	print(r)
	
if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

  那么就需要跳过HTTPS证书验证的过程,将其修改为:

# coding: utf-8
import urllib.request
import ssl


def main():
    ssl._create_default_https_context = ssl._create_unverified_context
    r = urllib.request.urlopen('https://bing.com')
    print(r.status)
    print(r)


if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

四、参考链接

[1] https://clay-atlas.com/us/blog/2021/09/26/python-en-urllib-error-ssl-certificate/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/182306
推荐阅读
相关标签
  

闽ICP备14008679号