scrapy框架之增量式爬虫
一 、增量式爬虫
什么时候使用增量式爬虫:
增量式爬虫:需求 当我们浏览一些网站会发现,某些网站定时的会在原有的基础上更新一些新的数据。如一些电影网站会实时更新最近热门的电影。那么,当我们在爬虫的过程中遇到这些情况时,我们是不是应该定期的更新程序以爬取到更新的新数据?那么,增量式爬虫就可以帮助我们来实现
二 、增量式爬虫
概念:
通过爬虫程序检测某网站数据更新的情况,这样就能爬取到该网站更新出来的数据
如何进行增量式爬取工作:
在发送请求之前判断这个URL之前是不是爬取过
在解析内容之后判断该内容之前是否爬取过
在写入存储介质时判断内容是不是在该介质中
增量式的核心是 去重
去重的方法:
将爬取过程中产生的URL进行存储,存入到redis中的set中,当下次再爬取的时候,对在存储的URL中的set中进行判断,如果URL存在则不发起请求,否则 就发起请求
对爬取到的网站内容进行唯一的标识,然后将该唯一标识存储到redis的set中,当下次再爬取数据的时候,在进行持久化存储之前,要判断该数据的唯一标识在不在redis中的set中,如果在,则不在进行存储,否则就存储该内容
三、示例
爬虫文件
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from redis import Redis from increment2_Pro.items import Increment2ProItem import hashlib class QiubaiSpider(CrawlSpider): name = \'qiubai\' # allowed_domains = [\'www.xxx.com\'] start_urls = [\'https://www.qiushibaike.com/text/\'] rules = ( Rule(LinkExtractor(allow=r\'/text/page/\\d+/\'), callback=\'parse_item\', follow=True), ) def parse_item(self, response): div_list = response.xpath(\'//div[@class=\"article block untagged mb15 typs_hot\"]\') conn = Redis(host=\'127.0.0.1\',port=6379) for div in div_list: item = Increment2ProItem() item[\'content\'] = div.xpath(\'.//div[@class=\"content\"]/span//text()\').extract() item[\'content\'] = \'\'.join(item[\'content\']) item[\'author\'] = div.xpath(\'./div/a[2]/h2/text() | ./div[1]/span[2]/h2/text()\').extract_first() # 将当前爬取的数据做哈希唯一标识(数据指纹) sourse = item[\'content\']+item[\'author\'] hashvalue = hashlib.sha256(sourse.encode()).hexdigest() ex = conn.sadd(\'qiubai_hash\',hashvalue) if ex == 1: yield item else: print(\'没有可更新的数据可爬取\') # item = {} #item[\'domain_id\'] = response.xpath(\'//input[@id=\"sid\"]/@value\').get() #item[\'name\'] = response.xpath(\'//div[@id=\"name\"]\').get() #item[\'description\'] = response.xpath(\'//div[@id=\"description\"]\').get() # return item
管道文件(管道文件也可以不用加)
from redis import Redis class Increment2ProPipeline(object): conn = None def open_spider(self,spider): self.conn = Redis(host=\'127.0.0.1\',port=6379) def process_item(self, item, spider): dic = { \'author\':item[\'author\'], \'content\':item[\'content\'] } self.conn.lpush(\'qiubaiData\',dic) print(\'爬取到一条数据,正在入库......\') return item
© 版权声明
THE END
暂无评论内容