发布于 3年前

python 爬虫:https; HTTPSConnectionPool(host='z.jd.com', port=443)

1. 第一种方案

import requests

requests.get('https://www.zhihu.com/',verify=False)

2.第二种方案

由于python2不支持SNI,具体SNI了解转:http://blog.csdn.net/makenothing/article/details/53292335 如果想python2支持SNI,pip安装3个模块:

1.pyOpenSSL

2.ndg-httpsclient

3.pyasn1

然后在使用requests请求前添加如下代码:

import urllib3.contrib.pyopenssl

urllib3.contrib.pyopenssl.inject_into_urllib3()


使用第一种方案解决的时候,出现以下警告:

InsecureRequestWarning: Unverified HTTPS requestisbeing made. Adding certificate verificationisstrongly advised.

在语句前加上以下代码即可不会被报错:requests.packages.urllib3.disable_warnings()


经过试验测试,第一,二种方案都会继续报错。

继续寻找方案(链接四):

使用requests下载日志出现:

HTTPSConnectionPool(host='***', port=443): Max retries exceeded with url: ******(Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),))

分析是ssl证书报错,解决办法:

1. requests默认是keep-alive的,可能没有释放,加参数 headers={'Connection':'close'}

requests..get("http://...", headers={'Connection':'close'})

2. 增加连接重试次数:

requests.adapters.DEFAULT_RETRIES =5

3. 关闭多余的连接:requests使用了urllib3库,默认的http connection是keep-alive的,requests设置False关闭。

s = requests.session()

s.keep_alive = False

操作方法:

s = requests.session()

s.keep_alive =False

4. 不用ssl证书验证:

requests.get('https://kennethreitz.org', verify=False)

使用(1,2,3)方法即可解决

©2020 edoou.com   京ICP备16001874号-3