没有输出的输入是不完整的

0%

Bug-Scrapy-Filtered_offsite_request

在写爬虫的时候遇见了一个bug,报错信息为 Filtered offsite request domain[‘mydomain’],
从网上找到了答案并成功解决了问题,特别记录一下。

检查allowed_domains

要去查看自己爬取的url是否符合我们的domain。如果我们要爬取的网站的网址为 https://www.example.com/1.html, 那么我们就需要添加example.com到我们写好的爬虫中的allowed_domains的list列表中。

1
allowed_domains = ['example.com']

看一下Scrapy官方文档的解释。

allowed_domains
An optional list of strings containing domains that this spider is allowed to crawl. Requests for URLs not belonging to the domain names specified in this list (or their subdomains) won’t be followed if OffsiteMiddleware is enabled.

也就是说,启用域名过滤后,请求的主机名必须属于 allowed_domains 中的域名或其子域,否则就会被过滤。仅在 URL 的其他位置出现这个字符串是不够的。

设置 dont_filter=True

可以让这个请求跳过重复请求过滤和 OffsiteMiddleware 的域名限制。也就是在新生成的Request中添加 dont_filter=True,比如下面这样。

1
2
3
4
def parse(self, response):
yield Request(url='https://example.com', dont_filter=True, callback=self.parse2)
def parse2(self, response):
pass

看一下Scrapy官方文档的解释:

dont_filter (boolean) – indicates that this request should not be filtered by the scheduler. This is used when you want to perform an identical request multiple times, to ignore the duplicates filter. Use it with care, or you will get into crawling loops. Default to False.

这个设置只影响当前请求,不会全局关闭过滤。不过它连重复请求检查也一起跳过了,如果不断生成相同请求,就可能陷入循环。所以还是优先检查 allowed_domains,确实需要时再用这个方法。

较新 Scrapy 如果只想跳过域名过滤,可参考 allow_offsite,并确认所用版本支持。

PS:一定要细心,我个人出现的问题是我想当然的设置了域名,然后真实网站的域名和我设置的域名差一个字母,所以最后就报错了。