Fork me on GitHub

scrapy自定义重试方法

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

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

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

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

scrapy/downloadermiddlewares/retry.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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采集了多少次,如果重试次数小于设置的最大重试次数,那么重试。

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

1
2
3
4
5
6
7
8
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传递。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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的继承。