解决 [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败问题
该错误提示 “[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed” 表明 Python 在尝试建立一个安全的 SSL 连接时无法验证远端服务器的 SSL 证书。这种情况通常是由于本地缺少必要的 CA 证书或证书库过时引起的。
对于 Python 2.7 特别常见,因为 Python 2.7 的支持已经在 2020 年初结束,其自带的证书可能已经过时。这里有几个解决方案可以尝试:
1. 忽略 SSL 证书验证
虽然不推荐(因为这样会降低安全性),但你可以在命令行中添加 --trusted-host
参数和 --index-url
参数来绕过 SSL 验证:
以下以pyperclip 为例,把pyperclip 换成自己需要安装的模块:
以下是一些国内的镜像使用示例,可以选择其中一个自测一下:
pip install pyperclip --trusted-host pypi.mirrors.ustc.edu.cn --index-url=http://pypi.mirrors.ustc.edu.cn/simple/
pip install pyperclip --trusted-host pypi.tuna.tsinghua.edu.cn --index-url=http://pypi.tuna.tsinghua.edu.cn/simple
pip install pyperclip --trusted-host mirrors.aliyun.com --index-url=http://mirrors.aliyun.com/pypi/simple/
pip install pyperclip --trusted-host pypi.douban.com --index-url=http://pypi.douban.com/simple/
pip install pyperclip --trusted-host mirrors.163.com --index-url=http://mirrors.163.com/pypi/simple/
请注意,这里使用的是 HTTP
而不是 HTTPS
,以避免 SSL 验证。
2. 更新 certifi 包
certifi
包包含了最新的 CA 证书数据。可以尝试手动下载并安装合适的 certifi
包:
-
从 PyPI certifi 页面 下载合适的
certifi
包。 -
使用
pip
安装下载的.whl
文件或.tar.gz
文件。例如:pip install /path/to/certifi-xxxx.whl
3. 手动安装模块
以下以pyperclip 为例:
可以尝试手动下载 pyperclip
的源代码,然后手动安装:
-
前往 PyPI pyperclip 页面,下载源代码包。(可以搜索自己需要的包)
-
解压下载的文件。
-
在命令行中导航到解压后的目录,运行以下命令安装:
python setup.py install
通过这些步骤,你应该能够解决 SSL 证书验证失败的问题并成功安装所需的包。