第一种方法

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爬虫多次请求超时的几种重试方法(6种)相关推荐

  1. python爬虫下载模块_python爬虫模块之HTML下载模块

    HTML下载模块 该模块主要是根据提供的url进行下载对应url的网页内容.使用模块requets-HTML,加入重试逻辑以及设定最大重试次数,同时限制访问时间,防止长时间未响应造成程序假死现象. 根 ...

  2. python requests下载网页_python爬虫 requests-html的使用

    一 介绍 Python上有一个非常著名的HTTP库--requests,相信大家都听说过,用过的人都说非常爽!现在requests库的作者又发布了一个新库,叫做requests-html,看名字也能猜 ...

  3. python爬虫下载模块_python爬虫——下载ted视频

    鄙人长期知乎潜水,这是我的第一篇知乎文章,如有不好的地方请多指教 自学爬虫一个月有余,又是一个英语学习爱好者,突然心血来朝想去ted上面看下如何爬视频 1.所用工具 requests模块 --爬虫核心 ...

  4. python爬虫下载模块_python爬虫系列(4.5-使用urllib模块方式下载图片)

    一.回顾urllib包中下载图片的方式 1.urlretrieve下载文件 from urllib import request if __name__ == "__main__" ...

  5. 用python重复下载文件_python 爬虫 重复下载 二次请求

    C:\Python27\python.exe C:/Users/xuchunlin/PycharmProjects/A9_25/auction/test.py 正在请求的URL是: https://w ...

  6. python爬虫超时重试_Python爬虫实例(三):错误重试,超时处理

    错误重试 错误重试用到的方法之一是:@retry()装饰器html 装饰器实际是一个python函数,它的做用就是为被装饰的函数(或对象)进行装饰.包装,可让被装饰的函数(或对象)在不须要作任何代码改 ...

  7. python爬虫开发环境_python爬虫开发教程下载|Python爬虫开发与项目实战(范传辉 著)pdf 完整版_ - 极光下载站...

    Python爬虫开发与项目实战pdf扫描版下载.Python爬虫开发是一个Pthyon编程语言与HTML基础知识引领读者入门知识,重点讲述了云计算的相关内容及其在爬虫中的应用,进而介绍如何设计自己的爬 ...

  8. 爬虫python教程百度云_Python爬虫比较基础的教程视频百度云网盘下载

    Python爬虫比较基础的教程视频百度云网盘下载,目录如下,给编程的朋友学习吧,请大家支持正版! QQ截图20180719110859.jpg (12.41 KB, 下载次数: 27) 2018-7- ...

  9. python爬虫快速下载图片_Python爬虫入门:批量爬取网上图片的两种简单实现方式——基于urllib与requests...

    Python到底多强大,绝对超乎菜鸟们(当然也包括我了)的想象.近期我接触到了爬虫,被小小地震撼一下.总体的感觉就两个词--"强大"和"有趣".今天就跟大家分享 ...

  10. python爬虫网络中断_Python 爬虫总是超时中断?试试Tenacity重试模块

    为了避免由于一些网络或等其他不可控因素,而引起的功能性问题.比如在发送请求时,会因为网络不稳定,往往会有请求超时的问题. 这种情况下,我们通常会在代码中加入重试的代码.重试的代码本身不难实现,但如何写 ...

最新文章

  1. tarjan详解(转)
  2. AI 经典书单 | 人工智能学习该读哪些书
  3. java闪屏怎么制作,Java Swing创建自定义闪屏:在闪屏下画进度条(一)
  4. 共享一PYTHON 相关应用领域的介绍资料
  5. log4j2.xml 的标签 loggers 中 root 的属性 level 指的是什么
  6. window 之命令行的cd
  7. 视频质量检测中的TP、FP、Reacll、Precision
  8. 漫游飞行_除了防打扰,手机飞行模式还有这些作用
  9. 如何在 macOS Monterey 正式发布之前备份您的 Automator 作品?
  10. Linux电源驱动-Linux Cpuidle Framework
  11. python 批量爬取网页pdf_python爬取网页内容转换为PDF文件
  12. 红米手机4X获得Root权限的流程
  13. 4133:垃圾炸弹 百练noi Java枚举
  14. 如何处理“WLAN没有有效的IP配置”这一问题?
  15. 星级评分原理 N次重写的分析
  16. 十六进制字符串与byte数组与ASCII码互相转换
  17. [UOJ198]时空旅行
  18. AMA专题: 深入解读Read2N三大创新, 全面启动市场引擎
  19. nba app android,NBA app官方版
  20. docker学习——bind mounts

热门文章

  1. qq空间登陆 cookie_看完这篇 Session、Cookie、Token,和面试官扯皮就没问题了||CSDN博文精选...
  2. mysql添加字典子项_如何使用executemany在MySQL中插入Python字典列表
  3. qt 二次开发 研华daq_研华DAQ数据采集卡编程
  4. 反恐精英的服务器存在哪个文件夹,反恐精英地图放在哪里 CS1.6地图放置位置详细介绍_游侠网...
  5. asp.net oracle 分页,asp.net教程之利用ASP实现Oracle数据记录的分页显示
  6. 电脑网络怎么添加计算机,Win10系统如何添加网络共享打印机
  7. mysql用大白话解释_大白话解释给小白如何看别人的源码(一)数据库部分
  8. 基于JAVA+SSH+MYSQL的工资管理系统
  9. 一键生成安卓证书_【带壳截图+电影台词 生成器】
  10. 标自然段的序号格式_你可能还不会基本的公文格式