首页 > 解决方案 > Python 3:urllib 模块基本功能不起作用

问题描述

我是一名新的 python 开发人员,我在 YouTube 上观看了一些教程,解释了这个模块的功能和用途,但我无法让它工作。我通过 pip 安装了模块,所以我认为这不是问题。

import urllib.request

x = urllib.request.urlopen('https://www.google.com')

print(x.read())

输出:

回溯(最后一次调用):文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py”,第 1342 行,在 do_open h.request(req.get_method() , req.selector, req.data, headers, File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1255, in request self._send_request(method, url, body, headers, encode_chunked) 文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py”,第 1301 行,在 _send_request self.endheaders(body, encode_chunked=encode_chunked )文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py”,第1250行,在endheaders self._send_output(message_body,encode_chunked=encode_chunked)文件“/Library/Frameworks /Python.framework/Versions/3.9/lib/python3.9/http/client.py",第 1010 行,在 _send_output self.send(msg) 文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py”,第 950 行,在发送 self.connect() 文件中“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py”,第 1424 行,在 connect self.sock = self._context.wrap_socket(self.sock, File "/Library /Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py",第 500 行,在 wrap_socket 中返回 self.sslsocket_class._create(File"/Library/Frameworks/Python.framework/Versions/3.9/lib /python3.9/ssl.py”,第 1040 行,在 _create self.do_handshake() 文件中“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py”,第 1309 行,在do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败:无法获取本地颁发者证书 (_ssl.c:1122)

在处理上述异常的过程中,又出现了一个异常:

Traceback(最近一次调用最后一次):文件“/Users/mike/PycharmProjects/urllib/main.py”,第 8 行,在 x = urllib.request.urlopen('https://www.google.com') 文件“ /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py”,第 214 行,在 urlopen 返回 opener.open(url, data, timeout) 文件“/Library/Frameworks/Python .framework/Versions/3.9/lib/python3.9/urllib/request.py”,第 517 行,打开响应 = self._open(req, data) 文件“/Library/Frameworks/Python.framework/Versions/3.9/ lib/python3.9/urllib/request.py",第 534 行,在 _open 结果 = self._call_chain(self.handle_open,协议,协议 + 文件"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3 .9/urllib/request.py”,第 494 行,在 _call_chain 结果 = func(*args) 文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py",第 1385 行,在 https_open 返回 self.do_open(http.client.HTTPSConnection, req, File"/Library/Frameworks/Python.framework/Versions/ 3.9/lib/python3.9/urllib/request.py",第 1345 行,在 do_open 中引发 URLError(err) urllib.error.URLError:<urlopen 错误 [SSL:CERTIFICATE_VERIFY_FAILED] 证书验证失败:无法获取本地颁发者证书( _ssl.c:1122)>1122)>1122)>

进程以退出代码 1 结束

标签: pythonhttpurlmodulerequest

解决方案


似乎是 SSL 证书错误。

可能您电脑上的某个程序正在阻止 SSL 证书。


推荐阅读