Python3處理HTTPS請求 SSL證書驗證
金融類的公司網站一般都是https 開頭的網站,urllib.request可以為 HTTPS 請求驗證SSL證書,就像web瀏覽器一樣,如果網站的SSL證書是經過CA認證的,則能夠正常訪問,如:
- 平安好伙伴出單系統:https://icore-pts.pingan.com.cn/ebusiness/login.jsp
- 浙商保險出單系統:https://core.zsins.com/pcis//core/main.jsp
例子一:編寫一個https請求程序訪問(平安好伙伴出單系統)
from urllib import parse
import urllib.request
url = 'https://icore-pts.pingan.com.cn/ebusiness/login.jsp'
headers ={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
}
# url 作為Request()方法的參數,構造並返回一個Request對象
request = urllib.request.Request(url,headers=headers)
# Request對象作為urlopen()方法的參數,發送給服務器並接收響應
response = urllib.request.urlopen(request)
html = response.read().decode('utf-8')
print(html)
通過例子,是可以正常訪問的,因為網站的SSL證書是經過CA認證的。
如果SSL證書驗證不通過,或者操作系統不信任服務器的安全證書,比如瀏覽器在訪問12306網站如:https://www.12306.cn/mormhweb/的時候,會警告用戶證書不受信任。(據說 12306 網站證書是自己做的,沒有通過CA認證)
例子二:編寫一個https請求程序訪問(12306網站)
from urllib import parse
import urllib.request
url = 'https://www.12306.cn/mormhweb/'
headers ={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
}
# url 作為Request()方法的參數,構造並返回一個Request對象
request = urllib.request.Request(url,headers=headers)
# Request對象作為urlopen()方法的參數,發送給服務器並接收響應
response = urllib.request.urlopen(request)
html = response.read().decode('utf-8')
print(html)
運行結果:
運行報錯:ssl.CertificateError: hostname 'www.12306.cn' doesn't match either of 'webssl.chinanetcenter.com'
通過查看urllib.request庫源碼文件
如果網站的SSL證書是經過CA認證,就需要單獨處理SSL證書,讓程序忽略SSL證書驗證錯誤,即可正常訪問。
例子三:12306網站或略SSL證書驗證
from urllib import parse
import urllib.request
# 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 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
}
# url 作為Request()方法的參數,構造並返回一個Request對象
request = urllib.request.Request(url,headers=headers)
# Request對象作為urlopen()方法的參數,發送給服務器並接收響應
# 3. 在urlopen()方法里 指明添加 context 參數
response = urllib.request.urlopen(request,context = context)
html = response.read().decode('utf-8')
print(html)
運行結果:
通過例子,證明我們的處理是成功的。
---------------------------------------
個人今日頭條賬號: 聽海8 (上面上傳了很多相關學習的視頻以及我書里的文章,大家想看視頻,可以關注我的今日頭條)