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
上面的代码包含以下方法 –
- parse() – 它将提取我们感兴趣的链接。
 - 
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)
极客教程