使用BeautifulSoup進(jìn)行網(wǎng)絡(luò)抓取數(shù)據(jù),SSL: CERTIFICATE_VERIFY_FAILED報錯

from urllib.request import urlopen

from bs4 import BeautifulSoup

import sys

import ssl

context = ssl._create_unverified_context()

html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon", context=context)

bsObj = BeautifulSoup(html)

for link in bsObj.findAll("a"):

? ? if 'href' in link.attrs:

? ? ? ? print(link.attrs["href"])

問題:??

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake

? ? self._sslobj.do_handshake()

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

“SSL: CERTIFICATE_VERIFY_FAILED”。

Python 升級到 2.7.9 之后引入了一個新特性,當(dāng)使用urllib.urlopen打開一個 https 鏈接時,會驗(yàn)證一次 SSL 證書。

解決方案包括下列兩種方式:

1. 使用ssl創(chuàng)建未經(jīng)驗(yàn)證的上下文,在urlopen中傳入上下文參數(shù)

import? ssl?

import urllib2

context = ssl._create_unverified_context()

print urllib2.urlopen("https://www.12306.cn/mormhweb/", context=context).read()

2. 全局取消證書驗(yàn)證

import ssl

importurllib2?

ssl._create_default_https_context =ssl._create_unverified_context

printurllib2.urlopen("https://www.12306.cn/mormhweb/").read()

在此使用方法2,修改weibo.py,在第155行添加下列代碼:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

至此,問題圓滿解決!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容