解決python打開https出現(xiàn)certificate verify failed的問(wèn)題
今天遇到一個(gè)奇怪的問(wèn)題,在用urllib打開一個(gè)https鏈接的時(shí)候,出現(xiàn)了一下報(bào)錯(cuò)信息:IOError: [Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727),報(bào)錯(cuò)問(wèn)題就是證書驗(yàn)證失敗,這種情況出現(xiàn)在網(wǎng)站使用的是自簽名證書或系統(tǒng)根證書存在問(wèn)題的時(shí)候。
原因:
Python 從 2.7.9版本開始,就默認(rèn)開啟了服務(wù)器證書驗(yàn)證功能,如果證書校驗(yàn)不通過(guò),則拒絕后續(xù)操作;這樣可以防止中間人攻擊,并使客戶端確保服務(wù)器確實(shí)是它聲稱的身份。如果是自簽名證書,由于一般系統(tǒng)的CA證書中不存在在自簽名的CA證書內(nèi)容,從而導(dǎo)致證書驗(yàn)證不通過(guò)。
臨時(shí)解決方案
方案1:通過(guò)環(huán)境部變量設(shè)置,關(guān)閉服務(wù)器證書驗(yàn)證功能
執(zhí)行以下shell命令(假設(shè)你使用的是bash shell):
echo 'export PYTHONHTTPSVERIFY=0' >> ~/.bashrc
source ~/.bashrc
方案2:取消服務(wù)器證書驗(yàn)證功能(全局影響)
在文件開始部分,加入如下代碼:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
方案3:創(chuàng)建取消服務(wù)器證書驗(yàn)證的context參數(shù)(當(dāng)前請(qǐng)求代碼影響)
使用示例如下:
import sslcontext = ssl._create_unverified_context()urllib.urlopen(’https://www.baidu.com’, context=context)
方案4:requests verify 參數(shù)設(shè)置為False,取消驗(yàn)證功能
使用示例如下:
requests.get(url, verify=False)
方案5:手動(dòng)指定CA證書(Python3)
使用示例如下:
import urllib
urllib.request.urlopen('https://example.com/some/info', cafile='ca.pem')
當(dāng)系統(tǒng)根證書存在問(wèn)題的時(shí)候,可以使用 certifi提供的CA證書:
import certifiimport urlliburllib.request.urlopen(’https://example.com/bar/baz.html’, cafile=certifi.where())
補(bǔ)充知識(shí):Python3之關(guān)閉SSL證書驗(yàn)證
報(bào)錯(cuò)信息:
Traceback (most recent call last):File 'D:Python36libsite-packagesurllib3contribpyopenssl.py', line 441, in wrap_socketcnx.do_handshake()File 'D:Python36libsite-packagesOpenSSLSSL.py', line 1806, in do_handshakeself._raise_ssl_error(self._ssl, result)File 'D:Python36libsite-packagesOpenSSLSSL.py', line 1546, in _raise_ssl_error_raise_current_error()File 'D:Python36libsite-packagesOpenSSL_util.py', line 54, in exception_from_error_queueraise exception_type(errors)OpenSSL.SSL.Error: [(’SSL routines’, ’tls_process_server_certificate’, ’certificate verify failed’)]
During handling of the above exception, another exception occurred:
https://aweme.snssdk.com/aweme/v1/play/?video_id=v0200f180000bc4e71kd1dr48pievrrg&line=0&app_id=24
因?yàn)榫W(wǎng)址使用了https,所以經(jīng)過(guò)代理時(shí)會(huì)報(bào)錯(cuò);
解決方案:
#參數(shù):verify=Falsehtml = requests.get(item_url, headers=headers, verify=False)# print(html.content)
以上這篇解決python打開https出現(xiàn)certificate verify failed的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python 合并拼接字符串的方法2. python使用jenkins發(fā)送企業(yè)微信通知的實(shí)現(xiàn)3. Python3 json模塊之編碼解碼方法講解4. 通過(guò)實(shí)例解析Python文件操作實(shí)現(xiàn)步驟5. ASP基礎(chǔ)知識(shí)VBScript基本元素講解6. Python 制作查詢商品歷史價(jià)格的小工具7. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條8. PHP使用Swagger生成好看的API文檔9. Python 利用Entrez庫(kù)篩選下載PubMed文獻(xiàn)摘要的示例10. Python 如何調(diào)試程序崩潰錯(cuò)誤

網(wǎng)公網(wǎng)安備