macOS 10.12.5
在 Python 3.6 及以上的版本中,直接发送 HTTPS 请求,会出现以下问题
[SSL: CERTIFICATE_VERIFY_FAILED]
这个问题兜一圈才注意到 Python 安装目录下 ReadMe.rtf 中说明了这个问题
Certificate verification and OpenSSL
****NEW**** This variant of Python 3.6 now includes its own private copy of OpenSSL 1.0.2. Unlike previous releases, the deprecated Apple-supplied OpenSSL libraries are no longer used. This also means that the trust certificates in system and user keychains managed by the *Keychain Access *application and the security command line utility are no longer used as defaults by the Python ssl module. For 3.6.0, a sample command script is included in /Applications/Python 3.6 to install a curated bundle of default root certificates from the third-party
certifi
package (https://pypi.python.org/pypi/certifi). If you choose to usecertifi
, you should consider subscribing to the project's email update service to be notified when the certificate bundle is updated.The bundled pip included with the Python 3.6 installer has its own default certificate store for verifying download connections.
大致意思就是,Python 不再使用由系统提供的证书,且本身也并不包含证书,需要安装 certifi
的证书包。
不过在安装目录下,有一个 Install Certificates.command
的脚本,运行即可安装 certifi
,会将证书复制到正确的目录下,并设置好权限。
也可以在支持选择证书文件的方法中手动加入,如
import urllib
import certifi
request = urllib.request.Request('https://secure.address.com')
urllib.request.urlopen(request, cafile=certifi.where())
另外还有一个不推荐的方法解决这个问题
使用不验证 SSL 证书的方式发送请求
import ssl
urllib.request.urlopen(request, context=ssl._create_unverified_context())