zl程序教程

您现在的位置是:首页 >  Python

当前栏目

爬虫系列4:scrapy技术进阶之多页面爬取

2023-04-18 14:49:33 时间

多页面爬取有两种形式。

1)从某一个或者多个主页中获取多个子页面的url列表,parse()函数依次爬取列表中的各个子页面。

2)从递归爬取,这个相对简单。在scrapy中只要定义好初始页面以及爬虫规则rules,就能够实现自动化的递归爬取。

获取子页面url列表的代码示例如下:

#先获取url list,然后根据list爬取各个子页面内容 fromtutorial.items import DmozItem

classDmozSpider(scrapy.Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls =["http://www.dmoz.org/Computers/Programming/Languages/Python/",]

def parse(self, response): for href inresponse.css("ul.directory.dir-col > li > a::attr('href')"): #获取当前页面的url:respone.url #通过拼接response.url和href.extract(),将相对网址转换为绝对网址 url =response.urljoin(response.url, 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