您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:python爬虫scrapy框架之增量式爬虫的示例代码

51自学网 2021-10-30 22:54:04
  python
这篇教程python爬虫scrapy框架之增量式爬虫的示例代码写得很实用,希望能帮到您。

scrapy框架之增量式爬虫

一 、增量式爬虫

什么时候使用增量式爬虫:
增量式爬虫:需求 当我们浏览一些网站会发现,某些网站定时的会在原有的基础上更新一些新的数据。如一些电影网站会实时更新最近热门的电影。那么,当我们在爬虫的过程中遇到这些情况时,我们是不是应该定期的更新程序以爬取到更新的新数据?那么,增量式爬虫就可以帮助我们来实现

二 、增量式爬虫

概念:
通过爬虫程序检测某网站数据更新的情况,这样就能爬取到该网站更新出来的数据

如何进行增量式爬取工作:
在发送请求之前判断这个URL之前是不是爬取过
在解析内容之后判断该内容之前是否爬取过
在写入存储介质时判断内容是不是在该介质中

增量式的核心是 去重
去重的方法:
将爬取过程中产生的URL进行存储,存入到redis中的set中,当下次再爬取的时候,对在存储的URL中的set中进行判断,如果URL存在则不发起请求,否则 就发起请求
对爬取到的网站内容进行唯一的标识,然后将该唯一标识存储到redis的set中,当下次再爬取数据的时候,在进行持久化存储之前,要判断该数据的唯一标识在不在redis中的set中,如果在,则不在进行存储,否则就存储该内容

三、示例

爬虫文件

# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom redis import Redisfrom increment2_Pro.items import Increment2ProItemimport hashlibclass 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 Redisclass 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

到此这篇关于python爬虫之scrapy框架之增量式爬虫的示例代码的文章就介绍到这了,更多相关scrapy增量式爬虫内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


详解Python openpyxl库的基本应用
python lambda的使用详解
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。