python爬蟲scrapy框架之增量式爬蟲的示例代碼
scrapy框架之增量式爬蟲
一 、增量式爬蟲什么時候使用增量式爬蟲:增量式爬蟲:需求 當(dāng)我們?yōu)g覽一些網(wǎng)站會發(fā)現(xiàn),某些網(wǎng)站定時的會在原有的基礎(chǔ)上更新一些新的數(shù)據(jù)。如一些電影網(wǎng)站會實時更新最近熱門的電影。那么,當(dāng)我們在爬蟲的過程中遇到這些情況時,我們是不是應(yīng)該定期的更新程序以爬取到更新的新數(shù)據(jù)?那么,增量式爬蟲就可以幫助我們來實現(xiàn)
二 、增量式爬蟲概念:通過爬蟲程序檢測某網(wǎng)站數(shù)據(jù)更新的情況,這樣就能爬取到該網(wǎng)站更新出來的數(shù)據(jù)
如何進(jìn)行增量式爬取工作:在發(fā)送請求之前判斷這個URL之前是不是爬取過在解析內(nèi)容之后判斷該內(nèi)容之前是否爬取過在寫入存儲介質(zhì)時判斷內(nèi)容是不是在該介質(zhì)中
增量式的核心是 去重去重的方法:將爬取過程中產(chǎn)生的URL進(jìn)行存儲,存入到redis中的set中,當(dāng)下次再爬取的時候,對在存儲的URL中的set中進(jìn)行判斷,如果URL存在則不發(fā)起請求,否則 就發(fā)起請求對爬取到的網(wǎng)站內(nèi)容進(jìn)行唯一的標(biāo)識,然后將該唯一標(biāo)識存儲到redis的set中,當(dāng)下次再爬取數(shù)據(jù)的時候,在進(jìn)行持久化存儲之前,要判斷該數(shù)據(jù)的唯一標(biāo)識在不在redis中的set中,如果在,則不在進(jìn)行存儲,否則就存儲該內(nèi)容
三、示例爬蟲文件
# -*- 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() # 將當(dāng)前爬取的數(shù)據(jù)做哈希唯一標(biāo)識(數(shù)據(jù)指紋) sourse = item[’content’]+item[’author’] hashvalue = hashlib.sha256(sourse.encode()).hexdigest() ex = conn.sadd(’qiubai_hash’,hashvalue) if ex == 1:yield item else:print(’沒有可更新的數(shù)據(jù)可爬取’) # 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(’爬取到一條數(shù)據(jù),正在入庫......’) return item
到此這篇關(guān)于python爬蟲之scrapy框架之增量式爬蟲的示例代碼的文章就介紹到這了,更多相關(guān)scrapy增量式爬蟲內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
