增量式爬虫

增量式爬虫

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

增量式爬虫

  • 概念:经过爬虫程序监测某网站数据更新的状况,以即可以爬取到该网站更新出的新数据。dom

  • 如何进行增量式的爬取工做:scrapy

  • 在发送请求以前判断这个URL是否是以前爬取过
  • 在解析内容后判断这部份内容是否是以前爬取过
  • 写入存储介质时判断内容是否是已经在介质中存在ide

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

    • 将爬取过程当中产生的url进行存储,存储在redis的set中。当下次进行数据爬取时,首先对即将要发起的请求对应的url在存储的url的set中作判断,若是存在则不进行请求,不然才进行请求。url

    • 对爬取到的网页内容进行惟一标识的制定,而后将该惟一表示存储至redis的set中。当下次爬取到网页数据的时候,在进行持久化存储以前,首先能够先判断该数据的惟一标识在redis的set中是否存在,在决定是否进行持久化存储。spa

案例: 爬取4567tv网站中全部的电影详情数据

爬虫文件:code

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from redis import Redis
from incrementPro.items import IncrementproItem
class MovieSpider(CrawlSpider):
    name = 'movie'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['http://www.4567tv.tv/frim/index7-11.html']

    rules = (
        Rule(LinkExtractor(allow=r'/frim/index7-\d+\.html'), callback='parse_item', follow=True),
    )
    #建立redis连接对象
    conn = Redis(host='127.0.0.1',port=6379)
    def parse_item(self, response):
        li_list = response.xpath('//li[@class="p1 m1"]')
        for li in li_list:
            #获取详情页的url
            detail_url = 'http://www.4567tv.tv'+li.xpath('./a/@href').extract_first()
            #将详情页的url存入redis的set中
            ex = self.conn.sadd('urls',detail_url)
            if ex == 1:
                print('该url没有被爬取过,能够进行数据的爬取')
                yield scrapy.Request(url=detail_url,callback=self.parst_detail)
            else:
                print('数据尚未更新,暂无新数据可爬取!')

    #解析详情页中的电影名称和类型,进行持久化存储
    def parst_detail(self,response):
        item = IncrementproItem()
        item['name'] = response.xpath('//dt[@class="name"]/text()').extract_first()
        item['kind'] = response.xpath('//div[@class="ct-c"]/dl/dt[4]//text()').extract()
        item['kind'] = ''.join(item['kind'])
        yield item

管道文件:htm

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

from redis import Redis
class IncrementproPipeline(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 = {
            'name':item['name'],
            'kind':item['kind']
        }
        print(dic)
        self.conn.lpush('movieData',dic)
        return item

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

爬虫文件:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from incrementByDataPro.items import IncrementbydataproItem
from redis import Redis
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),
        Rule(LinkExtractor(allow=r'/text/$'), callback='parse_item', follow=True),
    )
    #建立redis连接对象
    conn = Redis(host='127.0.0.1',port=6379)
    def parse_item(self, response):
        div_list = response.xpath('//div[@id="content-left"]/div')

        for div in div_list:
            item = IncrementbydataproItem()
            item['author'] = div.xpath('./div[1]/a[2]/h2/text() | ./div[1]/span[2]/h2/text()').extract_first()
            item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            #将解析到的数据值生成一个惟一的标识进行redis存储
            source = item['author']+item['content']
            source_id = hashlib.sha256(source.encode()).hexdigest()
            #将解析内容的惟一表示存储到redis的data_id中
            ex = self.conn.sadd('data_id',source_id)

            if ex == 1:
                print('该条数据没有爬取过,能够爬取......')
                yield item
            else:
                print('该条数据已经爬取过了,不须要再次爬取了!!!')

管道文件:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

from redis import Redis
class IncrementbydataproPipeline(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']
        }
        # print(dic)
        self.conn.lpush('qiubaiData', dic)
        return item
相关文章
相关标签/搜索