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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM