python:爬虫遇到的问题[requests卡住](多次请求超时的几种重试方式)

您所在的位置:网站首页 怎么抢卡住了 python:爬虫遇到的问题[requests卡住](多次请求超时的几种重试方式)

python:爬虫遇到的问题[requests卡住](多次请求超时的几种重试方式)

2024-07-17 22:47| 来源: 网络整理| 查看: 265

爬虫问题系列文章目录

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 爬虫遇到的问题[requests卡住]多次请求超时的几种重试方式

文章目录 爬虫问题系列文章目录前言第一种第三种第五种总结

前言

在爬虫的过程中,遇到请求卡住,进行重试这样的方法很常见的

在网上找到了几种方法进行总结 以下是原文章地址: python爬虫多次请求超时的几种重试方式:作者[it_is_arlon] 下面来看看这位作者是怎么写的

提示:以下是本篇文章正文内容,下面案例可供参考

第一种 headers = Dict() url = 'https://www.baidu.com' try: proxies = None response = requests.get(url, headers=headers, verify=False, proxies=None, timeout=3) except: # logdebug('requests failed one time') try: proxies = None response = requests.get(url, headers=headers, verify=False, proxies=None, timeout=3) except: # logdebug('requests failed two time') print('requests failed two time')

总结 :代码比较冗余,重试try的次数越多,代码行数越多,但是打印日志比较方便

# 第二种 def requestDemo(url,): headers = Dict() trytimes = 3 # 重试的次数 for i in range(trytimes): try: proxies = None response = requests.get(url, headers=headers, verify=False, proxies=None, timeout=3) # 注意此处也可能是302等状态码 if response.status_code == 200: break except: # logdebug(f'requests failed {i}time') print(f'requests failed {i} time')

总结 :遍历代码明显比第一个简化了很多,打印日志也方便

第三种 def requestDemo(url, times=1): headers = Dict() try: proxies = None response = requests.get(url, headers=headers, verify=False, proxies=None, timeout=3) html = response.text() # todo 此处处理代码正常逻辑 pass return html except: # logdebug(f'requests failed {i}time') trytimes = 3 # 重试的次数 if times


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3