爬虫Retrying模块

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/gklcsdn/article/details/102700926

爬虫模块 – retrying用法

在做爬虫的时候经常会碰到因为网络原因, 或者在使用代理ip的时候, 碰到ip不可用的情况, 需要多次访问的时候, 就可以用到retrying这个模块了… 使用方式如下

1. 安装
pip install retrying
2. Retrying源码
class Retrying(object):
    """
    	以下时间均为毫秒
    	stop_max_attempt_number: 最大重试次数
		wait_random_min: 随机等待最小时间。
		wait_random_max:  随机等待最大时间。
		stop_max_delay: 最大重试时间
		wait_fixed: 两次调用方法停留时长
		wait_incrementing_increment: 每调用一次增加时长
    """

    def __init__(self,
                 stop=None, wait=None,
                 stop_max_attempt_number=None,
                 stop_max_delay=None,
                 wait_fixed=None,
                 wait_random_min=None, wait_random_max=None,
                 wait_incrementing_start=None, wait_incrementing_increment=None,
                 wait_exponential_multiplier=None, wait_exponential_max=None,
                 retry_on_exception=None,
                 retry_on_result=None,
                 wrap_exception=False,
                 stop_func=None,
                 wait_func=None,
                 wait_jitter_max=None):
        pass
  
3. 使用方式(以装饰器形式调用)
# coding: utf8

import time
import requests
from retrying import retry

# 出现异常时最多访问3次, 每次时间间隔3s
@retry(stop_max_attempt_number=3, wait_fixed=3000)
def spider():
    print('*'*20)
    url = 'www.baidu.com'
    response = requests.get(url).content.decode('utf-8')
    print(response)


def parse():
    try:
        spider()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    parse()


猜你喜欢

转载自blog.csdn.net/gklcsdn/article/details/102700926