CERTIFICATE_VERIFY_FAILED 解決方法

for Windows + Anaconda + Python 3

用 Python requests 要到台北科技教育網抓取網站資料時,會遇到 SSL: CERTIFICATE_VERIFY_FAILED 錯誤,而瀏覽器(如Chrome)都沒有問題,原因是環境中 (windows + anaconda) 沒有台北科技教育網 SSL 所要的憑證

import requests

requests.get("https://techpro.tp.edu.tw/manager/cms/taipei-edu/scartch.html")


SSLError: HTTPSConnectionPool(host='techpro.tp.edu.tw', port=443): Max retries exceeded with url: /manager/cms/taipei-edu/scartch.html (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)'),))

如果只是測試,那關掉認證就可以解決,但還是有警告提示。

requests.get("https://techpro.tp.edu.tw/manager/cms/taipei-edu/scartch.html", verify=False)


C:\Users\ManaTsao\.conda\envs\tensorflowenv\lib\site-packages\urllib3\connectionpool.py:986: InsecureRequestWarning: Unverified HTTPS request is being made to host 'techpro.tp.edu.tw'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

InsecureRequestWarning,

若要徹底解決問題,就要將憑證加到環境中。步驟如下:

1. 先更新 certifi :

在 andaconda prompt 中執行

pip install certifi

pip install -U pyopenssl

若此時再執行 requests.get 沒有出錯,那就不必繼續下面的步驟。

2. 找出台北科技教育網所用的認證:

在 Chrome 中打開台北教育網後,按 F12 進入開發人員工具模式,並選擇 Security

Chrome F12 中的security

找到用的是 RapidSSL RSA CA 2018。點 View Certificate 進去找一下是哪一家公司發行的,是 digicert 這家公司。

3. 接著到 Google 搜尋 “RapidSSL RSA CA 2018 download” 並找到 digicert 的網頁

注意是digicert的網頁

注意是digicert的網頁

一路可以找到下載的地方

找到下載的地方

找到下載的地方

點選 Download PEM 下載 RapidSSLRSACA2018.crt.pem , 用文字編輯器打開,大概長這樣:

RapidSSLRSACA2018.crt.pem 的內容

RapidSSLRSACA2018.crt.pem 的內容

4. 回到 Jupyter Notebook 執行

import certifi

certifi.where()

執行結果:

'C:\\Users\\ManaTsao\\.conda\\envs\\tensorflowenv\\lib\\site-packages\\certifi\\cacert.pem'

找到該檔案,也用文字編輯器打開,內容會像是這樣:

cacert.pem 的內容

cacert.pem 的內容

5. 接著把網頁上 Rapid SSL RSA 的說明,copy 到 cacert.pem 的最下方,再 copy RapidSSLRSACA2018.crt.pem 裡面所有的內容,結果如下:

加上 RapidSSLRSACA2018.crt.pem 的結果

加上 RapidSSLRSACA2018.crt.pem 的結果

完成後記得存檔

6. 回到 Jupyter Notebook 重新執行

import requests

requests.get("https://techpro.tp.edu.tw/manager/cms/taipei-edu/scartch.html")

就不會有錯誤或警告了,結果如下:

<Response [200]>

第一次發此類文,只是把這幾天受的苦、網路爬的文做個記錄,希望能幫到大家。Bye now~