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 升級(jí)到 2.7.9 之后引入了一個(gè)新特性唱蒸,當(dāng)使用urllib.urlopen打開一個(gè) https 鏈接時(shí)碧磅,會(huì)驗(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
至此适室,問題圓滿解決嫡意!