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

2023-05-12,,

多页面爬取有两种形式。

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

爬虫系列4:scrapy技术进阶之多页面爬取的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。