爬虫遇到 HTTPSConnectionPool(host=‘xxxxx‘, port=443) 解决思路

admin 2023年2月23日12:39:25Python评论4,818 次浏览阅读模式

1、原因  SSL 证书报错

  1. http连接太多没有关闭导致的。

  2. 经过一番查询,发现该错误是因为如下:

  3. http的连接数超过最大限制,默认的情况下连接是Keep-alive的,所以这就导致了服务器保持了太多连接而不能再新建连接。

  4. 1、ip被封

  5. 2、程序请求速度过快。

2、解决方式

(1)time.sleep()

(2)关闭 SSL 验证   verify=False

response = requests.get(fpath_or_url,headers=headers,stream=True, verify=False)

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

  1. sess = requests.Session()

  2. sess.mount('http://', HTTPAdapter(max_retries=3))

  3. sess.mount('https://', HTTPAdapter(max_retries=3))

  4. sess.keep_alive = False

  5. text = requests.get(self.target_img_url, headers=headers, stream=True, verify=False, timeout=(5,5))

  6. with open(img_files_path, 'wb') as file:

  7. for i in text.iter_content(1024 * 10):

  8. file.write(i)

  9. text.close()

(4) 改变重连次数 requests.adapters.DEFAULT_RETRIES = 5

  1. try:

  2. headers = {

  3. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',

  4. }

  5. sess = requests.Session()

  6. sess.mount('http://', HTTPAdapter(max_retries=3))

  7. sess.mount('https://', HTTPAdapter(max_retries=3))

  8. sess.keep_alive = False

  9. text = requests.get(self.target_img_url, headers=headers, stream=True, verify=False, timeout=(5,5))

  10. with open(img_files_path, 'wb') as file:

  11. for i in text.iter_content(1024 * 10):

  12. file.write(i)

  13. text.close()

  14. except Exception as e:

  15. print(e,self.target_img_url)

(5) 其他 忽略警告信息

3、Reference

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

相关文章
weinxin
我的微信
微信扫一扫
admin
  • 本文由 发表于 2023年2月23日12:39:25
  • 转载请务必保留本文链接:https://anyun.org/a/jishuguanzhu/bianchengchalou/python/2023/0223/12794.html