前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >scrapy自定义重试方法

scrapy自定义重试方法

作者头像
小歪
发布2019-03-07 14:47:42
2.3K0
发布2019-03-07 14:47:42
举报
文章被收录于专栏:Python爬虫与算法进阶

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

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

[scrapy/downloadermiddlewares/retry.py]

https://github.com/scrapy/scrapy/blob/master/scrapy/downloadermiddlewares/retry.py#L63

代码语言:javascript
复制
    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采集了多少次,如果重试次数小于设置的最大重试次数,那么重试。

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

代码语言:javascript
复制
    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传递。

代码语言:javascript
复制
    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的继承。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-01-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python爬虫与算法进阶 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档