1. 程式人生 > >HTTPS請求 SSL證書驗證

HTTPS請求 SSL證書驗證

cer import failed blog kit urllib2 highlight www. header

import urllib2

url = "https://www.12306.cn/mormhweb/"

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}

request = urllib2.Request(url, headers = headers)

response = urllib2.urlopen(request)

print response.read()

  

運行結果:

urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)>

所以,如果以後遇到這種網站,我們需要單獨處理SSL證書,讓程序忽略SSL證書驗證錯誤,即可正常訪問。

import urllib
import urllib2
# 1. 導入Python SSL處理模塊
import ssl

# 2. 表示忽略未經核實的SSL證書認證
context = ssl._create_unverified_context()

url = "https://www.12306.cn/mormhweb/"

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}

request = urllib2.Request(url, headers = headers)

# 3. 在urlopen()方法裏 指明添加 context 參數
response = urllib2.urlopen(request, context = context)

print response.read()

  

HTTPS請求 SSL證書驗證