Python使用requests模块访问HTTPS网站报错`certificate verify failed`

使用requests模块访问HTTPS网站报错:

SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/data1/sleep/env/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Traceback (most recent call last):
  File "test_demo1.py", line 16, in <module>
    f()
  File "test_demo1.py", line 13, in f
    r=requests.post(url,json=data,headers=header,)
  File "/data1/env/lib/python2.7/site-packages/requests/api.py", line 107, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/data1/env/lib/python2.7/site-packages/requests/api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "/data1/env/lib/python2.7/site-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/data1/env/lib/python2.7/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/data1/env/lib/python2.7/site-packages/requests/adapters.py", line 447, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

看到两个警告,查看警告提供的网站发现,是因为在2.7.9之前的Python版本,urllib3的ssl比较旧,就会导致这个错。
解决方法是安装urllib3[secure],也就是带安全模块的urllib3.

pip install urllib3[secure]
#如果装得很慢,就使用豆瓣的pip源
pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
#如果报错不支持参数--trusted-host,就升级pip
pip install --upgrade pip

安装后,一般就可以访问了。
如果还是不行,就要重新安装requests模块

pip uninstall requests
pip install  requests
    原文作者:Xjng
    原文地址: https://www.cnblogs.com/Xjng/p/6844446.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞