解決Python certificate verify failed的問題

來源:互聯網
上載者:User

在使用 urllib2.urlopen開啟https時,報錯:urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)>

出現此錯誤的原因是目標網站的https認證不是在認證簽發機構購買的。

問題的原因是“SSL: CERTIFICATE_VERIFY_FAILED”。

Python 升級到 2.7.9 之後引入了一個新特性,當使用urllib.urlopen開啟一個 https 連結時,會驗證一次 SSL 憑證。

而當目標網站使用的是自簽名的認證時就會拋出一個 urllib2.URLError: 的錯誤訊息,詳細資料可以在這裡查看(https://www.python.org/dev/peps/pep-0476/)。


解決方案:


1.使用ssl建立未經驗證的上下文,在urlopen中傳入上下文參數

import ssl
import urllib2
 
context = ssl._create_unverified_context()
print urllib2.urlopen("https://www.111cn.net/", context=context).read()

2.匯入ssl時關閉認證驗證

import ssl
import urllib2
 
ssl._create_default_https_context = ssl._create_unverified_context
print urllib2.urlopen("https://www.111cn.net/").read()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.