Python3處理HTTPS請求 SSL證書驗證


Python3處理HTTPS請求 SSL證書驗證

金融類的公司網站一般都是https 開頭的網站,urllib.request可以為 HTTPS 請求驗證SSL證書,就像web瀏覽器一樣,如果網站的SSL證書是經過CA認證的,則能夠正常訪問,如:

  1. 平安好伙伴出單系統:https://icore-pts.pingan.com.cn/ebusiness/login.jsp
  2. 浙商保險出單系統: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   (上面上傳了很多相關學習的視頻以及我書里的文章,大家想看視頻,可以關注我的今日頭條)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM