解决 Python 报错 CERTIFICATE_VERIFY_FAILED: certificate verify failed 根证书修复指南
排查 Python 使用 urllib 与 requests 请求 HTTPS 接口提示 SSL: CERTIFICATE_VERIFY_FAILED 错误,分析 macOS 安装脚本与 certifi 库配置。
问题现象
在 macOS 或 Linux 上运行 Python 脚本爬取数据或调用第三方 API 时,抛出底层的 SSL 校验崩溃:
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)>
或者使用 requests 库时抛出:
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))
触发根因
在 Python 3.6+ 环境下,Python 默认严格开启 HTTPS 主机名与证书签名校验:
- macOS 官方 Python 安装包未初始化证书:在 macOS 上通过官方
.pkg安装的 Python,默认自带独立的 OpenSSL 副本,但为了合规并不直接使用 macOS 钥匙串,而是附带了一个Install Certificates.command脚本;若用户安装后未双击执行该脚本,Python 内部缺少任何可信根证书; certifi依赖包损坏或版本过旧:第三方库certifi内置的根证书集合没有包含新的根 CA;- 企业代理或内网自建证书拦截。
解决步骤
1. 运行 macOS 官方证书安装脚本(针对 macOS 用户)
在终端中执行对应 Python 版本的内置安装脚本:
# 针对 Python 3.10
/Applications/Python\ 3.10/Install\ Certificates.command
# 针对 Python 3.9
/Applications/Python\ 3.9/Install\ Certificates.command
脚本会自动使用 pip 安装最新的 certifi 并建立 /Library/Frameworks/Python.framework/Versions/X.X/etc/openssl/cert.pem 软链接。
2. 在虚拟环境中更新 certifi
在当前项目的虚拟环境中重新安装与更新证书依赖:
pip install --upgrade certifi
3. 在代码中显式指定 certifi 证书路径
在 Python 脚本中明确为 requests 传入合法的 CA 路径:
import certifi
import requests
response = requests.get('https://api.github.com', verify=certifi.where())
print(response.status_code)
4. 针对自建证书提供企业 CA 路径
如果调用的内部服务使用的是企业私有 CA:
response = requests.get('https://internal-api.example.com', verify='/path/to/company-ca.pem')
避免使用 verify=False,防止中间人嗅探与请求伪造攻击。
验证确认
在 Python 交互式环境中执行简单的请求测试:
python3 -c "import urllib.request; urllib.request.urlopen('https://www.google.com')"
命令瞬间执行完毕并安静退出,无任何 CERTIFICATE_VERIFY_FAILED 异常抛出,排查修复完成。


