解决 HTTPSConnectionPool 报错 requests.exceptions.SSLError
解决报错requests.exceptions.ConnectionError: HTTPSConnectionPool(host=‘xxx’, port=443): Max retries exceeded with url 使用requests时出错
整整耗了一个星期的时间,因为需要爬取百度汉语上的释义约60余万次,因为requests.exceptions.SSLError错误随机地导致程序停止,很是头疼。采用了网上大部分的方法如1-4都没有用,最终使用5的方法成功解决,其实很简单,就是requests请求网页时可能会请求不到,重试,加入try…except…语句即可解决。
一、先检查一下自己的库中是否装了下面三个库
# 没有的话请依次安装
pip install certifi
pip install cryptography
pip install pyOpenSSL
二、请在网页请求中加入:verify=False
# 没有的话请依次安装
pip install certifi
pip install cryptography
pip install pyOpenSSL
这个的含义是: requests设置移除SSL认证
response = requests.get(url, headers=headers,verify=False)
print(response)
# 但是可能会出现 InsecureRequestWarning 警告,
# 虽然不影响代码采集但是看着不舒服,可以加上下面两行:
import urllib3
urllib3.disable_warnings()
四、连接数过多
如果requests连接数很多,那么在请求中避免使用持久连接
可以在请求头headers中加入
headers = {'Connection': 'close'}
或者:
requests.adapters.DEFAULT_RETRIES = 5
五、可能出现的别的原因
1、设置session
import requests
session = requests.session()
...
response = session.get(url, headers=headers,verify=False)
print(response)
2、requests请求网页时可能会请求不到,重试,加入try…except…语句
try:
response = session.get(url, headers=headers,verify=False)
except:
response = session.get(url, headers=headers,verify=False)
print(response)