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写的图片蜘蛛人代码
Aug 27 Python
Python文件夹与文件的操作实现代码
Jul 13 Python
Python使用正则表达式抓取网页图片的方法示例
Apr 21 Python
python中Switch/Case实现的示例代码
Nov 09 Python
详解windows python3.7安装numpy问题的解决方法
Aug 13 Python
在python中使用requests 模拟浏览器发送请求数据的方法
Dec 26 Python
Python的条件表达式和lambda表达式实例
Jan 31 Python
通过cmd进入python的实例操作
Jun 26 Python
Python3.7安装keras和TensorFlow的教程图解
Jun 18 Python
Python 复平面绘图实例
Nov 21 Python
Python基于network模块制作电影人物关系图
Jun 19 Python
python数据处理之Pandas类型转换
Apr 28 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
PR值查询 | PageRank 查询
2006/12/20 PHP
PHP实现MySQL更新记录的代码
2008/06/07 PHP
php 动态多文件上传
2009/01/18 PHP
ThinkPHP CURD方法之field方法详解
2014/06/18 PHP
在win7中搭建Linux+PHP 开发环境
2014/10/08 PHP
PHP去除字符串最后一个字符的三种方法实例
2017/03/01 PHP
微信公众号开发之获取位置信息php代码
2018/06/13 PHP
PHP-FPM和Nginx的通信机制详解
2019/02/01 PHP
发两个小东西,ASP/PHP 学习工具。 用JavaScript写的
2007/04/12 Javascript
jQuery处理xml格式的返回数据(实例解析)
2013/11/28 Javascript
使用 TypeScript 重新编写的 JavaScript 坦克大战游戏代码
2015/04/07 Javascript
jQuery拖拽插件gridster使用指南
2015/04/21 Javascript
学习JavaScript设计模式之模板方法模式
2016/01/20 Javascript
jQuery实现百叶窗焦点图动画效果代码分享(附源码下载)
2016/03/14 Javascript
javascript检查某个元素在数组中的索引值
2016/03/30 Javascript
javascript小数精度丢失的完美解决方法
2016/05/31 Javascript
jq checkbox 的全选并ajax传参的实例
2017/04/01 Javascript
浅谈Node.js 沙箱环境
2018/05/15 Javascript
vue实现条件判断动态绑定样式的方法
2018/09/29 Javascript
Python调用C/C++动态链接库的方法详解
2014/07/22 Python
在Django框架中设置语言偏好的教程
2015/07/27 Python
python实现SMTP邮件发送功能
2020/06/16 Python
Flask入门之上传文件到服务器的方法示例
2018/07/18 Python
django 实现编写控制登录和访问权限控制的中间件方法
2019/01/15 Python
Python button选取本地图片并显示的实例
2019/06/13 Python
python打印9宫格、25宫格等奇数格 满足横竖斜相加和相等
2019/07/19 Python
python使用celery实现异步任务执行的例子
2019/08/28 Python
pytorch torch.nn.AdaptiveAvgPool2d()自适应平均池化函数详解
2020/01/03 Python
python GUI库图形界面开发之PyQt5访问系统剪切板QClipboard类详细使用方法与实例
2020/02/27 Python
浅谈python opencv对图像颜色通道进行加减操作溢出
2020/06/03 Python
python打开文件的方式有哪些
2020/06/29 Python
Python 实现集合Set的示例
2020/12/21 Python
如何写求职信
2014/05/24 职场文书
学生通报表扬范文
2015/05/04 职场文书
居委会工作总结2015
2015/05/18 职场文书
2015年超市工作总结范文
2015/05/26 职场文书