python爬虫 requests异常requests.exceptions.ConnectionError: HTTPSConnectionPool Max retries exceeded

错误提示:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='baike.baidu.com', port=443):
 Max retries exceeded with url: https://baike.baidu.com/item/%E5%88%98%E5%BE%B7%E5%8D%8E/114923
 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fb51433af98>:
 Failed to establish a new connection: [Errno -2] Name or service not known',))

经过一番查询,发现该错误是因为如下:
1.http的连接数超过最大限制,默认的情况下连接是Keep-alive的,所以这就导致了服务器保持了太多连接而不能再新建连接。
2.ip被封
3.程序请求速度过快。
解决方法如下:
第一种方法:

try:
    page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
	r = page1
    r.status_code = "Connection refused"

我的补充:事实上这种情况相当于越过了这一个没有连接成功的数据的爬取,如果你想要把连接失败的这一部分数据也进行读取,可以用一个数组先存储爬取失败的数据,然后循环完成之后再进行爬取

for data in tqdm(county_url_data):
    #data = 11/01/110101.html
    #爬取对应县的数据
    url = 'http://www.baidu.com'+data
    #county_url_data之中存放的为街道对应的数值
    try:
        resp = requests.get(url,headers=headers)
        current_data = resp.text.encode('ISO-8859-1').decode(requests.utils.get_encodings_from_content(resp.text)[0],'ignore')
    except:
        break_data.append(data)
        continue

for data in tqdm(break_data):
	接着对之前没有处理的数据进行操作

第二种方法
requests的连接数过多导致Max retries exceeded
在header中不使用持久连接

'Connection':'close'

第三种方法:
针对请求速度过快导致程序报错

import time
 
while 1:
    try:
        page = requests.get(url)
    except:
        print("Connection refused by the server..")
        print("Let me sleep for 5 seconds")
        print("ZZzzzz...")
        time.sleep(5)
        print("Was a nice sleep, now let me continue...")
        continue
http://www.chenxm.cc/post/536.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值