最近在做的短信发送,用response就可以正常的发送,但是用python的异步,去队列里发短信,就一直抱一个错:"[Errno 1] Cannot connect to host app.cloopen.com:8883 ssl:True [Can not connect to app.cloopen.com:8883 [[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)]]"
参考下边这个方法解决的:
python做爬虫,对于有的网站,需要验证证书,比如:12306,https://inv-veri.chinatax.gov.cn/等网站
那么我参考这个作者的简书:http://www.jianshu.com/p/e42005d48929 解决了这个错误:
加上一个参数:verify=证书路径,或verify=False
1 2 3 4 5 6 7 8 | #方法一<br>import requestsfrom bs4 import BeautifulSoupurl = '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,第二种简单的方法来了,下载啥安全证书?不需要,不需要。直接上一段添加证书代码:
1 | ssl._create_default_https_context = ssl._create_unverified_context#注意用了这个就不能用requests了,得用urllib2.Request |
完整代码如下:
1 2 3 4 5 6 7 8 9 | # 方法二(推荐):import sslimport urllib2ssl._create_default_https_context = ssl._create_unverified_contextreq = urllib2.Request('https://inv-veri.chinatax.gov.cn/')data = urllib2.urlopen(req).read()print(data) |
总结:经过我的测试,推荐大家使用方法二。喜欢的话点个赞哦~
经过大半年之后我又回到了爬虫:对于咱们上面两个方法我又发现了一个好的SSL证书验证的方法:加参数:verify=False
完整代码如下:
1 2 3 4 5 | #SSL证书验证import requestsresponse = requests.get('https://www.12306.cn', verify=False)print(response.status_code) |
不过我们发现报了一个警告,它建议我们给它指定证书。我们可以通过设置忽略警告的方式来屏蔽这个警告:
1 2 3 4 5 6 | import requestsfrom requests.packages import urllib3urllib3.disable_warnings()response = requests.get('https://www.12306.cn', verify=False)print(response.status_code) |
或者通过捕获警告到日志的方式忽略警告:
1 2 3 4 5 | import loggingimport requestslogging.captureWarnings(True)response = requests.get('https://www.12306.cn', verify=False)print(response.status_code) |
如果我上面三种方法还不能解决你ssl的错误的话,请重新安装requests:
1 | python2下载版本: |
1 | pip install requests==2.6.0 |
1 | python3下载版本 |
1 | pip install requests==2.7.0 |
再次运行成功。
示例:例如这个网址https://grwsyw.bjgjj.gov.cn/ish/,必须使用对的requests版本
:
1 2 3 | import requestsreq = requests.get('https://grwsyw.bjgjj.gov.cn/ish/',verify=False)print(req.text) |
