scrapy自定义重试方法

栏目: Python · 发布时间: 5年前

内容简介:自定义重试方法 (๑• . •๑)Scrapy是自带有重试的,但一般是下载出错才会重试,当然你可以在Middleware处来完成你的逻辑。这篇文章主要介绍的是如何在spider里面完成重试。使用场景比如,我解析json出错了,html中不包含我想要的数据,我要重试这个请求(request)。

scrapy自定义重试方法

这是崔斯特的第八十五篇原创文章

自定义重试方法 (๑• . •๑)

Scrapy是自带有重试的,但一般是下载出错才会重试,当然你可以在Middleware处来完成你的逻辑。这篇文章主要介绍的是如何在spider里面完成重试。使用场景比如,我解析json出错了,html中不包含我想要的数据,我要重试这个请求(request)。

我们先看看官方是如何完成重试的

scrapy/downloadermiddlewares/retry.py

def _retry(self, request, reason, spider):
    retries = request.meta.get('retry_times', 0) + 1

    retry_times = self.max_retry_times

    if 'max_retry_times' in request.meta:
        retry_times = request.meta['max_retry_times']

    stats = spider.crawler.stats
    if retries <= retry_times:
        logger.debug("Retrying %(request)s (failed %(retries)d times): %(reason)s",
                     {'request': request, 'retries': retries, 'reason': reason},
                     extra={'spider': spider})
        retryreq = request.copy()
        retryreq.meta['retry_times'] = retries
        retryreq.dont_filter = True
        retryreq.priority = request.priority + self.priority_adjust

        if isinstance(reason, Exception):
            reason = global_object_name(reason.__class__)

        stats.inc_value('retry/count')
        stats.inc_value('retry/reason_count/%s' % reason)
        return retryreq
    else:
        stats.inc_value('retry/max_reached')
        logger.debug("Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
                     {'request': request, 'retries': retries, 'reason': reason},
                     extra={'spider': spider})

可以看到非常清晰,在meta中传递一个参数 retry_times ,来记录当前的request采集了多少次,如果重试次数小于设置的最大重试次数,那么重试。

根据这段代码我们自定义的重试可以这么写

def parse(self, response):
    try:
        data = json.loads(response.text)

    except json.decoder.JSONDecodeError:
        r = response.request.copy()
        r.dont_filter = True
        yield r

捕获异常,如果返回不是json,那就重试,注意需要设置不过滤。

这种方法简单粗暴,存在BUG,就是会陷入死循环。我也可以记录重试的次数,用meta传递。

def parse(self, response):
    try:
        data = json.loads(response.text)

    except json.decoder.JSONDecodeError:
        retries = response.meta.get('cus_retry_times', 0) + 1
        if retries <= self.cus_retry_times:
            r = response.request.copy()
            r.meta['cus_retry_times'] = retries
            r.dont_filter = True
            yield r
        else:
            self.logger.debug("Gave up retrying {}, failed {} times".format(
                response.url, retries
            ))

这样就完成了自定义重试,你完全可以在中间件完成,但是我更喜欢这种方法,可以清楚地知道爬虫具体哪里会存在问题。

其实以上这种方法也不好,因为你可能会在很多地方都需要重试,每个函数都需要,那每次都写一遍,太不美观。更好的方法是将此方法封装为 scrapy.http.Response 的一个函数,需要用的时候直接调。代码就不贴了,有兴趣的可以研究下,用到 python 的继承。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

CSS与DHTML精髓(第2版)

CSS与DHTML精髓(第2版)

Dan Livingston / 清华大学 / 2003-7-1 / 34.00

CSS与DHTML精髓(第二版),ISBN:9787302066941,作者:战晓苏译;战晓苏译一起来看看 《CSS与DHTML精髓(第2版)》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具