• 17 增量式爬虫


      当我们在浏览相关网页的时候会发现,某些网站定时会在原有网页数据的基础上更新一批数据,例如某电影网站会实时更新一批最近热门的电影。小说网站会根据作者创作的进度实时更新最新的章节数据等等。那么,类似的情景,当我们在爬虫的过程中遇到时,我们是不是需要定时更新程序以便能爬取到网站中最近更新的数据呢?

    一.增量式爬虫

    • 概念:通过爬虫程序监测某网站数据更新的情况,以便可以爬取到该网站更新出的新数据。
    • 如何进行增量式的爬取工作:
      • 在发送请求之前判断这个URL是不是之前爬取过
      • 在解析内容后判断这部分内容是不是之前爬取过
      • 写入存储介质时判断内容是不是已经在介质中存在
        • 分析:

                不难发现,其实增量爬取的核心是去重, 至于去重的操作在哪个步骤起作用,只能说各有利弊。在我看来,前两种思路需要根据实际情况取一个(也可能都用)。第一种思路适合不断有新页面出现的网站,比如说小说的新章节,每天的最新新闻等等;第二种思路则适合页面内容会更新的网站。第三个思路是相当于是最后的一道防线。这样做可以最大程度上达到去重的目的。

    • 去重方法
      • 将爬取过程中产生的url进行存储,存储在redis的set中。当下次进行数据爬取时,首先对即将要发起的请求对应的url在存储的url的set中做判断,如果存在则不进行请求,否则才进行请求。
      • 对爬取到的网页内容进行唯一标识的制定,然后将该唯一表示存储至redis的set中。当下次爬取到网页数据的时候,在进行持久化存储之前,首先可以先判断该数据的唯一标识在redis的set中是否存在,在决定是否进行持久化存储。

    二.项目案例

    - 需求:爬取4567tv网站中所有的电影详情数据。

    爬虫文件:

     1 # -*- coding: utf-8 -*-
     2 import scrapy
     3 from scrapy.linkextractors import LinkExtractor
     4 from scrapy.spiders import CrawlSpider, Rule
     5 
     6 from redis import Redis
     7 from incrementPro.items import IncrementproItem
     8 class MovieSpider(CrawlSpider):
     9     name = 'movie'
    10     # allowed_domains = ['www.xxx.com']
    11     start_urls = ['http://www.4567tv.tv/frim/index7-11.html']
    12 
    13     rules = (
    14         Rule(LinkExtractor(allow=r'/frim/index7-d+.html'), callback='parse_item', follow=True),
    15     )
    16     #创建redis链接对象
    17     conn = Redis(host='127.0.0.1',port=6379)
    18     def parse_item(self, response):
    19         li_list = response.xpath('//li[@class="p1 m1"]')
    20         for li in li_list:
    21             #获取详情页的url
    22             detail_url = 'http://www.4567tv.tv'+li.xpath('./a/@href').extract_first()
    23             #将详情页的url存入redis的set中
    24             ex = self.conn.sadd('urls',detail_url)
    25             if ex == 1:
    26                 print('该url没有被爬取过,可以进行数据的爬取')
    27                 yield scrapy.Request(url=detail_url,callback=self.parst_detail)
    28             else:
    29                 print('数据还没有更新,暂无新数据可爬取!')
    30 
    31     #解析详情页中的电影名称和类型,进行持久化存储
    32     def parst_detail(self,response):
    33         item = IncrementproItem()
    34         item['name'] = response.xpath('//dt[@class="name"]/text()').extract_first()
    35         item['kind'] = response.xpath('//div[@class="ct-c"]/dl/dt[4]//text()').extract()
    36         item['kind'] = ''.join(item['kind'])
    37         yield item

    管道文件:

     1 # -*- coding: utf-8 -*-
     2 
     3 # Define your item pipelines here
     4 #
     5 # Don't forget to add your pipeline to the ITEM_PIPELINES setting
     6 # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
     7 
     8 from redis import Redis
     9 class IncrementproPipeline(object):
    10     conn = None
    11     def open_spider(self,spider):
    12         self.conn = Redis(host='127.0.0.1',port=6379)
    13     def process_item(self, item, spider):
    14         dic = {
    15             'name':item['name'],
    16             'kind':item['kind']
    17         }
    18         print(dic)
    19         self.conn.lpush('movieData',dic)
    20         return item

    - 需求:爬取糗事百科中的段子和作者数据。

    爬虫文件:

     1 # -*- coding: utf-8 -*-
     2 import scrapy
     3 from scrapy.linkextractors import LinkExtractor
     4 from scrapy.spiders import CrawlSpider, Rule
     5 from incrementByDataPro.items import IncrementbydataproItem
     6 from redis import Redis
     7 import hashlib
     8 class QiubaiSpider(CrawlSpider):
     9     name = 'qiubai'
    10     # allowed_domains = ['www.xxx.com']
    11     start_urls = ['https://www.qiushibaike.com/text/']
    12 
    13     rules = (
    14         Rule(LinkExtractor(allow=r'/text/page/d+/'), callback='parse_item', follow=True),
    15         Rule(LinkExtractor(allow=r'/text/$'), callback='parse_item', follow=True),
    16     )
    17     #创建redis链接对象
    18     conn = Redis(host='127.0.0.1',port=6379)
    19     def parse_item(self, response):
    20         div_list = response.xpath('//div[@id="content-left"]/div')
    21 
    22         for div in div_list:
    23             item = IncrementbydataproItem()
    24             item['author'] = div.xpath('./div[1]/a[2]/h2/text() | ./div[1]/span[2]/h2/text()').extract_first()
    25             item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first()
    26 
    27             #将解析到的数据值生成一个唯一的标识进行redis存储
    28             source = item['author']+item['content']
    29             source_id = hashlib.sha256(source.encode()).hexdigest()
    30             #将解析内容的唯一表示存储到redis的data_id中
    31             ex = self.conn.sadd('data_id',source_id)
    32 
    33             if ex == 1:
    34                 print('该条数据没有爬取过,可以爬取......')
    35                 yield item
    36             else:
    37                 print('该条数据已经爬取过了,不需要再次爬取了!!!')

    管道文件:

     1 # -*- coding: utf-8 -*-
     2 
     3 # Define your item pipelines here
     4 #
     5 # Don't forget to add your pipeline to the ITEM_PIPELINES setting
     6 # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
     7 
     8 from redis import Redis
     9 class IncrementbydataproPipeline(object):
    10     conn = None
    11 
    12     def open_spider(self, spider):
    13         self.conn = Redis(host='127.0.0.1', port=6379)
    14 
    15     def process_item(self, item, spider):
    16         dic = {
    17             'author': item['author'],
    18             'content': item['content']
    19         }
    20         # print(dic)
    21         self.conn.lpush('qiubaiData', dic)
    22         return item
  • 相关阅读:
    自然语言处理1-1 算法时间复杂度
    tensorflow2.0(1):简介
    基于PKCS#11的应用架构
    数字证书应用改造需求调研-2015-10-19
    签名验证工具Aloaha Sign
    PDF签名应用研究小结
    用bcp导sql server数据到excel文件
    无线网卡和有线网卡的嗅探模式的区别
    Tomcat6源代码在Eclipse里调试简要说明
    OpenLDAP 主从复制配置
  • 原文地址:https://www.cnblogs.com/a2534786642/p/10998727.html
Copyright © 2020-2023  润新知