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

318次阅读
没有评论
爬虫系列4:scrapy技术进阶之多页面爬取

多页面爬取有两种形式。

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

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-25发表,共计922字。
新手QQ群:570568346,欢迎进群讨论 Python51学习