引言
这一期的文章我们来分析一下 Scrapy 框架中 CrawSpider 类的源码,希望能够加深对其处理逻辑的理解。
CrawlSpider 源码分析
CrawlSpider 继承了 Spider,其入口函数是 start_requests,该函数的 callback 为 CrawlSpider 下的 _parse 函数。
def _parse(self, response, **kwargs):
return self._parse_response(
response=response,
callback=self.parse_start_url,
cb_kwargs=kwargs,
follow=True,
)
_parse 函数 (不要覆盖该函数!) 会调用 _parse_response (主函数),该函数允许自己定义 parse_start_url 和 process_results,然后允许调用 spider 文件中设置的 rules,将 response 交给 LinkExtractor,根据其中的参数 (可定制) 做预处理。
def _parse_response(self, response, callback, cb_kwargs, follow=True):
if callback:
cb_res = callback(response, **cb_kwargs) or ()
cb_res = self.process_results(response, cb_res)
for request_or_item