在本章中,我们将研究如何提取我们感兴趣的页面的链接,关注它们并从该页面提取数据.为此,我们需要在之前的代码中进行以下更改,如下所示 :
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)