Python 3 urllib ignore SSL certificate verification

Posted in :

在python 透過 request 下載遠端伺服器上 https 的資源時, 會發生錯誤, 有可能是因為憑證是自簽的, 也可能是連線不穩定造成, 錯誤訊息:

urlopen error [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure

解法:
https://stackoverflow.com/questions/36600583/python-3-urllib-ignore-ssl-certificate-verification

import ssl
import urllib.request

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

with urllib.request.urlopen(url_string, context=ctx) as f:
    f.read(300)

Alternatively, if you use requests library, it has much better API:

import requests

with open(file_name, 'wb') as f:
    resp = requests.get(url_string, verify=False)
    f.write(resp.content)

The answer is copied from this post (thanks @falsetru): How do I disable the ssl check in python 3.x?

替代解法 2:

import requests.packages.urllib3.util.ssl_
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL'

替代解法 3:

import requests
import warnings
from urllib3.exceptions import InsecureRequestWarning
warnings.simplefilter('ignore',InsecureRequestWarning)
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *