赞
踩
笔者是在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)
报错就是因为代码里面默认HTTPS是需要对SSL证书进行验证。因此只要关闭证书验证,代码就能正常运行。
在使用urllib.req(est.urlopen()
这个代码的文件开头写入如下代码,关闭SSL证书验证。
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
如运行代码如下代码报错
:
import urllib.request
def main():
r = urllib.request.urlopen('https://bing.com')
print(r.status)
print(r)
if __name__ == '__main__':
main()
那么就需要跳过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] https://clay-atlas.com/us/blog/2021/09/26/python-en-urllib-error-ssl-certificate/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。