python爬虫多次请求超时的几种重试方法(6种)


Posted in Python onDecember 01, 2020

第一种方法

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 < trytimes:
  times += 1
   return requestDemo(url, times)
  return 'out of maxtimes'

总结 :迭代 显得比较高大上,中间处理代码时有其它错误照样可以进行重试; 缺点 不太好理解,容易出错,另外try包含的内容过多时,对代码运行速度不利。

第四种方法

@retry(3) # 重试的次数 3
def requestDemo(url):
 headers = Dict()
 proxies = None
 response = requests.get(url, headers=headers, verify=False, proxies=None, timeout=3)
 html = response.text()
 # todo 此处处理代码正常逻辑
 pass
 return html
 
def retry(times):
 def wrapper(func):
  def inner_wrapper(*args, **kwargs):
   i = 0
   while i < times:
    try:
     print(i)
     return func(*args, **kwargs)
    except:
     # 此处打印日志 func.__name__ 为say函数
     print("logdebug: {}()".format(func.__name__))
     i += 1
  return inner_wrapper
 return wrapper

总结 :装饰器优点 多种函数复用,使用十分方便

第五种方法

#!/usr/bin/python
# -*-coding='utf-8' -*-
import requests
import time
import json
from lxml import etree
import warnings
warnings.filterwarnings("ignore")

def get_xiaomi():
 try:
  # for n in range(5): # 重试5次
  #  print("第"+str(n)+"次")
  for a in range(5): # 重试5次
   print(a)
   url = "https://www.mi.com/"
   headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
    "Connection": "keep-alive",
    # "Cookie": "xmuuid=XMGUEST-D80D9CE0-910B-11EA-8EE0-3131E8FF9940; Hm_lvt_c3e3e8b3ea48955284516b186acf0f4e=1588929065; XM_agreement=0; pageid=81190ccc4d52f577; lastsource=www.baidu.com; mstuid=1588929065187_5718; log_code=81190ccc4d52f577-e0f893c4337cbe4d|https%3A%2F%2Fwww.mi.com%2F; Hm_lpvt_c3e3e8b3ea48955284516b186acf0f4e=1588929099; mstz=||1156285732.7|||; xm_vistor=1588929065187_5718_1588929065187-1588929100964",
    "Host": "www.mi.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36"
   }
   response = requests.get(url,headers=headers,timeout=10,verify=False)
   html = etree.HTML(response.text)
   # print(html)
   result = etree.tostring(html)
   # print(result)
   print(result.decode("utf-8"))
   title = html.xpath('//head/title/text()')[0]
   print("title==",title)
   if "左左" in title:
   # print(response.status_code)
   # if response.status_code ==200:
    break
  return title

 except:
  result = "异常"
  return result

if __name__ == '__main__':
 print(get_xiaomi())

第六种方法

Python重试模块retrying

# 设置最大重试次数
@retry(stop_max_attempt_number=5)
def get_proxies(self):
 r = requests.get('代理地址')
 print('正在获取')
 raise Exception("异常")
 print('获取到最新代理 = %s' % r.text)
 params = dict()
 if r and r.status_code == 200:
  proxy = str(r.content, encoding='utf-8')
  params['http'] = 'http://' + proxy
  params['https'] = 'https://' + proxy
# 设置方法的最大延迟时间,默认为100毫秒(是执行这个方法重试的总时间)
@retry(stop_max_attempt_number=5,stop_max_delay=50)
# 通过设置为50,我们会发现,任务并没有执行5次才结束!

# 添加每次方法执行之间的等待时间
@retry(stop_max_attempt_number=5,wait_fixed=2000)
# 随机的等待时间
@retry(stop_max_attempt_number=5,wait_random_min=100,wait_random_max=2000)
# 每调用一次增加固定时长
@retry(stop_max_attempt_number=5,wait_incrementing_increment=1000)

# 根据异常重试,先看个简单的例子
def retry_if_io_error(exception):
 return isinstance(exception, IOError)

@retry(retry_on_exception=retry_if_io_error)
def read_a_file():
 with open("file", "r") as f:
  return f.read()

read_a_file函数如果抛出了异常,会去retry_on_exception指向的函数去判断返回的是True还是False,如果是True则运行指定的重试次数后,抛出异常,False的话直接抛出异常。

当时自己测试的时候网上一大堆抄来抄去的,意思是retry_on_exception指定一个函数,函数返回指定异常,会重试,不是异常会退出。真坑人啊!

来看看获取代理的应用(仅仅是为了测试retrying模块)

到此这篇关于python爬虫多次请求超时的几种重试方法的文章就介绍到这了,更多相关python爬虫多次请求超时内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
跟老齐学Python之画圈还不简单吗?
Sep 20 Python
Python元组操作实例分析【创建、赋值、更新、删除等】
Jul 24 Python
Python中的默认参数实例分析
Jan 29 Python
基于Python Numpy的数组array和矩阵matrix详解
Apr 04 Python
使用python生成杨辉三角形的示例代码
Aug 29 Python
pandas 条件搜索返回列表的方法
Oct 30 Python
python 切换root 执行命令的方法
Jan 19 Python
Python实现Mysql数据统计及numpy统计函数
Jul 15 Python
ubuntu 18.04 安装opencv3.4.5的教程(图解)
Nov 04 Python
Python字符串hashlib加密模块使用案例
Mar 10 Python
python 服务器运行代码报错ModuleNotFoundError的解决办法
Sep 16 Python
matplotlib 使用 plt.savefig() 输出图片去除旁边的空白区域
Jan 05 Python
python爬虫搭配起Bilibili唧唧的流程分析
Dec 01 #Python
python爬虫看看虎牙女主播中谁最“顶”步骤详解
Dec 01 #Python
详解Django自定义图片和文件上传路径(upload_to)的2种方式
Dec 01 #Python
使用python爬取抖音app视频的实例代码
Dec 01 #Python
基于Python实现粒子滤波效果
Dec 01 #Python
Django集成MongoDB实现过程解析
Dec 01 #Python
基于Django快速集成Echarts代码示例
Dec 01 #Python
You might like
PHP+javascript液晶时钟
2006/10/09 PHP
php in_array 函数使用说明与in_array需要注意的地方说明
2010/04/13 PHP
ThinkPHP框架实现导出excel数据的方法示例【基于PHPExcel】
2018/05/12 PHP
PHP-FPM 的管理和配置详解
2019/02/17 PHP
thinkPHP事务操作简单案例分析
2019/10/17 PHP
ThinkPHP5&amp;5.1实现验证码的生成、使用及点击刷新功能示例
2020/02/07 PHP
jQuery Tools Dateinput使用介绍
2012/07/14 Javascript
JQuery做的一个简单的点灯游戏分享
2014/07/16 Javascript
JavaScript indexOf方法入门实例(计算指定字符在字符串中首次出现的位置)
2014/10/17 Javascript
一步步教大家编写酷炫的导航栏js+css实现
2016/03/14 Javascript
js学习阶段总结(必看篇)
2016/06/16 Javascript
移动端web滚动分页的实现方法
2017/05/05 Javascript
Vue自定义事件(详解)
2017/08/19 Javascript
小程序云开发部署攻略(图文教程)
2018/10/30 Javascript
vue实现表单未编辑或未保存离开弹窗提示功能
2020/04/08 Javascript
Vue中keep-alive组件的深入理解
2020/08/23 Javascript
深入理解NumPy简明教程---数组1
2016/12/17 Python
python3爬取各类天气信息
2018/02/24 Python
python执行精确的小数计算方法
2019/01/21 Python
python 协程 gevent原理与用法分析
2019/11/22 Python
CSS3中使用RGBa来调节透明度的教程
2016/05/09 HTML / CSS
基于Html5实现的语音搜索功能
2019/05/13 HTML / CSS
ProBikeKit澳大利亚:自行车套件,跑步和铁人三项装备
2016/11/30 全球购物
澳大利亚排名第一的儿童在线玩具商店:Toy Galaxy
2018/10/06 全球购物
澳大利亚工具仓库:Tools Warehouse
2018/10/15 全球购物
用你熟悉的语言写一个连接ORACLE数据库的程序,能够完成修改和查询工作
2012/06/11 面试题
实习教师个人的自我评价
2013/11/08 职场文书
中学教师岗位职责
2013/11/26 职场文书
饭店工作计划书
2014/01/10 职场文书
西柏坡导游词
2015/02/05 职场文书
民主评议党员个人自我评价
2015/03/03 职场文书
2015年三万活动总结
2015/03/25 职场文书
2015年保险公司工作总结
2015/04/24 职场文书
2016年师德先进个人事迹材料
2016/02/29 职场文书
浅谈Python数学建模之线性规划
2021/06/23 Python
Ubuntu18.04下QT开发Android无法连接设备问题解决实现
2022/06/01 Java/Android