python爬蟲scrapy框架之增量式爬蟲的示例代碼
scrapy框架之增量式爬蟲
一 、增量式爬蟲什么時候使用增量式爬蟲:增量式爬蟲:需求 當我們?yōu)g覽一些網(wǎng)站會發(fā)現(xiàn),某些網(wǎng)站定時的會在原有的基礎上更新一些新的數(shù)據(jù)。如一些電影網(wǎng)站會實時更新最近熱門的電影。那么,當我們在爬蟲的過程中遇到這些情況時,我們是不是應該定期的更新程序以爬取到更新的新數(shù)據(jù)?那么,增量式爬蟲就可以幫助我們來實現(xiàn)
二 、增量式爬蟲概念:通過爬蟲程序檢測某網(wǎng)站數(shù)據(jù)更新的情況,這樣就能爬取到該網(wǎng)站更新出來的數(shù)據(jù)
如何進行增量式爬取工作:在發(fā)送請求之前判斷這個URL之前是不是爬取過在解析內容之后判斷該內容之前是否爬取過在寫入存儲介質時判斷內容是不是在該介質中
增量式的核心是 去重去重的方法:將爬取過程中產(chǎn)生的URL進行存儲,存入到redis中的set中,當下次再爬取的時候,對在存儲的URL中的set中進行判斷,如果URL存在則不發(fā)起請求,否則 就發(fā)起請求對爬取到的網(wǎng)站內容進行唯一的標識,然后將該唯一標識存儲到redis的set中,當下次再爬取數(shù)據(jù)的時候,在進行持久化存儲之前,要判斷該數(shù)據(jù)的唯一標識在不在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() # 將當前爬取的數(shù)據(jù)做哈希唯一標識(數(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
到此這篇關于python爬蟲之scrapy框架之增量式爬蟲的示例代碼的文章就介紹到這了,更多相關scrapy增量式爬蟲內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. java加載屬性配置properties文件的方法2. PHP正則表達式函數(shù)preg_replace用法實例分析3. php redis setnx分布式鎖簡單原理解析4. CSS3中Transition屬性詳解以及示例分享5. 什么是Python變量作用域6. js select支持手動輸入功能實現(xiàn)代碼7. 如何在PHP中讀寫文件8. 《Java程序員修煉之道》作者Ben Evans:保守的設計思想是Java的最大優(yōu)勢9. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼10. vue使用moment如何將時間戳轉為標準日期時間格式
