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

處理HTTPS請求 SSL證書驗證

現在隨處可見 https 開頭的網站,urllib2可以為 HTTPS 請求驗證SSL證書,就像web瀏覽器一樣,如果網站的SSL證書是經過CA認證的,則能夠正常訪問,如:https://www.baidu.com/等...如果SSL證書驗證不通過,或者作業系統不信任伺服器的安全證書,比如瀏覽器在訪問12306網站如:https://www.12306.cn/mormhweb/的時候,會警告使用者證書不受信任。

一般會報著樣的錯

 

(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

#解決辦法1

 

import ssl
from urllib import request
#表示忽略未經核實的ssl正書認證
ssl._create_default_https_context = ssl._create_unverified_context
base_url = 'https://www.wbiao.cn'
response = request.urlopen(base_url)
print(response.read().decode('utf-8'))

#解決辦法2

 

import requests
from lxml import etree
base_url = 'https://www.wbiao.cn'
#加verify=False
response = requests.get(base_url,verify=False)
response.encoding = response.apparent_encoding
html = response.text
print(html)
html = etree.HTML(html)
a_url = html.xpath('//div[@class="nav_left_menu"]//dd[@class="rel fl elps1"]/a[@rel="nofollow"]/@href')
print(a_url)

#第二種方法會報一個警告報錯,直接忽視就可以!

如有錯誤請指出,謝謝!