Scrapy跟踪链接

在本章中,我们将研究如何提取感兴趣页面的链接,并关注它们并从该页面提取数据。为此,我们需要对以前的代码进行如下更改,如下所示:

import scrapy
from tutorial.items import DmozItem

class MyprojectSpider(scrapy.Spider):
   name = "project"
   allowed_domains = ["dmoz.org"]

   start_urls = [
      "http://www.dmoz.org/Computers/Programming/Languages/Python/",
   ]
   def parse(self, response):
      for href in response.css("ul.directory.dir-col > li > a::attr('href')"):
         url = response.urljoin(href.extract())
            yield scrapy.Request(url, callback = self.parse_dir_contents)

   def parse_dir_contents(self, response):
      for sel in response.xpath('//ul/li'):
         item = DmozItem()
         item['title'] = sel.xpath('a/text()').extract()
         item['link'] = sel.xpath('a/@href').extract()
         item['desc'] = sel.xpath('text()').extract()
         yield item

以上代码包含以下方法:

  • 解析() - 它会提取我们感兴趣的链接。
  • response.urljoin - parse()方法将使用此方法构建新的url并提供一个新的请求,稍后将发送给回调。
  • parse_dir_contents() - 这是一个回调,它实际上会刮掉感兴趣的数据。

在这里,Scrapy使用回调机制来跟踪链接。使用这种机制,可以设计更大的爬行器,并可以按照感兴趣的链接从不同页面中抓取所需数据。常规方法将是回调方法,该方法将提取项目,查找指向下一页的链接,然后提供相同回调的请求。

以下示例将生成一个循环,该循环将链接到下一页。

def parse_articles_follow_next_page(self, response):
   for article in response.xpath("//article"):
      item = ArticleItem()

      ... extract article data here

      yield item

   next_page = response.css("ul.navigation > li.next-page > a::attr('href')")
   if next_page:
      url = response.urljoin(next_page[0].extract())
      yield scrapy.Request(url, self.parse_articles_follow_next_page)

存储数据的最佳方法是使用Feed输出,这可确保使用多个序列化格式正确存储数据。JSON,JSON行,CSV,XML是序列化格式中支持的格式。数据可以通过以下命令存储:scrapy crawl dmoz -o data ...