python requests SSL证书问题

错误信息如下:

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

  python做爬虫,对于有的网站,需要验证证书,比如:12306,https://inv-veri.chinatax.gov.cn/等网站

那么我参考这个作者的简书:http://www.jianshu.com/p/e42005d48929 解决了这个错误:

加上一个参数:verify=证书路径,或verify=False

#方法一
import requests from bs4 import BeautifulSoup url = 'https://inv-veri.chinatax.gov.cn/' req = requests.get(url,verify=False) req.encoding = 'utf-8' soup = BeautifulSoup(req.text,'lxml') print(soup)

  错误消失了但是有提醒,不过没事,可以解析出源代码。然后我根据他的简书继续下载证书,但是不知道为什么,我下载的证书不管用,然后没辙,幸好之前做过12306这个网站。OK,第二种简单的方法来了,下载啥安全证书?不需要,不需要。直接上一段添加证书代码:

ssl._create_default_https_context = ssl._create_unverified_context#注意用了这个就不能用requests了,得用urllib2.Request

  完整代码如下:

# 方法二(推荐):

import ssl
import urllib2

ssl._create_default_https_context = ssl._create_unverified_context
req = urllib2.Request('https://inv-veri.chinatax.gov.cn/')
data = urllib2.urlopen(req).read()
print(data)

  

  总结:经过我的测试,推荐大家使用方法二。喜欢的话点个赞哦~

 

经过大半年之后我又回到了爬虫:对于咱们上面两个方法我又发现了一个好的SSL证书验证的方法:加参数:verify=False

完整代码如下:

#SSL证书验证
import requests

response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)

不过我们发现报了一个警告,它建议我们给它指定证书。我们可以通过设置忽略警告的方式来屏蔽这个警告:

import requests
from requests.packages import urllib3

urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)

或者通过捕获警告到日志的方式忽略警告:

import logging
import requests
logging.captureWarnings(True)
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)

 如果我上面三种方法还不能解决你ssl的错误的话,请重新安装requests:

python2下载版本:
pip install requests==2.6.0  
python3下载版本
pip install requests==2.7.0 

再次运行成功。

示例:例如这个网址https://grwsyw.bjgjj.gov.cn/ish/,必须使用对的requests版本

import requests
req = requests.get('https://grwsyw.bjgjj.gov.cn/ish/',verify=False)
print(req.text)

 参考链接:https://blog.csdn.net/liujinz72213/article/details/78866873

posted @ 2017-09-05 17:40  那时的吻狠陶醉  阅读(34048)  评论(0编辑  收藏  举报