阅读量:0
场景:代码没有报错,而且确定 xpath 表达式正确解析。
可能的原因是:你使用了 Scrapy 对重复的 url 进行请求。
Scrapy 内置了重复过滤功能,默认情况下该功能处于打开状态。
如下实例,parse2 无法被调用:
import scrapy class ExampleSpider(scrapy.Spider): name ="test" # allowed_domains = ["https://www.baidu.com/"] start_urls = ["https://www.baidu.com/"] def parse(self,response): yield scrapy.Request(self.start_urls[0],callback=self.parse2) def parse2(self, response): print(response.url)
Scrapy 在进入 parse 时,会默认请求一次 start_urls[0],而当你在 parse 中又对 start_urls[0] 进行请求时,Scrapy 底层会默认过滤掉重复的 url,不会对该请求进行提交,这就是为什么 parse2 不被调用的原因。
解决方法:
添加 dont_filter=True 参数,这样 Scrapy 就不会过滤掉重复的请求。
import scrapy class ExampleSpider(scrapy.Spider): name ="test" # allowed_domains = ["https://www.baidu.com/"] start_urls = ["https://www.baidu.com/"] def parse(self,response): yield scrapy.Request(self.start_urls[0],callback=self.parse2,dont_filter=True) def parse2(self, response): print(response.url)
此时,parse2 会被正常调用。