Python:Scrapy框架中Item Pipeline組件使用詳解
Item Pipeline簡介
Item管道的主要責(zé)任是負責(zé)處理有蜘蛛從網(wǎng)頁中抽取的Item,他的主要任務(wù)是清晰、驗證和存儲數(shù)據(jù)。
當(dāng)頁面被蜘蛛解析后,將被發(fā)送到Item管道,并經(jīng)過幾個特定的次序處理數(shù)據(jù)。
每個Item管道的組件都是有一個簡單的方法組成的Python類。
他們獲取了Item并執(zhí)行他們的方法,同時他們還需要確定的是是否需要在Item管道中繼續(xù)執(zhí)行下一步或是直接丟棄掉不處理。
Item管道通常執(zhí)行的過程有
清理HTML數(shù)據(jù)
驗證解析到的數(shù)據(jù)(檢查Item是否包含必要的字段)
檢查是否是重復(fù)數(shù)據(jù)(如果重復(fù)就刪除)
將解析到的數(shù)據(jù)存儲到數(shù)據(jù)庫中
編寫自己的Item Pipeline
編寫item管道其實是很容易的。
每個Item管道的組件都是由一個簡單的方法組成的Python類:
process_item(item, spider)
每一個item管道組件都會調(diào)用該方法,并且必須返回一個item對象實例或raise DropItem異常。
被丟掉的item將不會在管道組件進行執(zhí)行
此外,我們也可以在類中實現(xiàn)以下方法
open_spider(spider)
當(dāng)spider執(zhí)行的時候?qū)⒄{(diào)用該方法
close_spider(spider)
當(dāng)spider關(guān)閉的時候?qū)⒄{(diào)用該方法
Item Pipeline例子
代碼如下:
from scrapy.exceptions import DropItem class PricePipeline(object): vat_factor = 1.15 def process_item(self, item, spider): if item['price']: if item['price_excludes_vat']: item['price'] = item['price'] * self.vat_factor return item else: raise DropItem("Missing price in %s" % item)
注:VAT:ValueAddedTax(增值稅)
以上代碼可以過濾那些沒有價格的產(chǎn)品,并且對那些不包括增值稅產(chǎn)品的價格進行調(diào)整
將抓取的items以json格式保存到文件中
從spider抓取到的items將被序列化為json格式,并且以每行一個item的形式被寫入到items.jl文件中
代碼:
import json class JsonWriterPipeline(object): def __init__(self): self.file = open('items.jl', 'wb') def process_item(self, item, spider): line = json.dumps(dict(item)) + "\n" self.file.write(line) return item
注:JsonWriterPipeline的目的是介紹如何編寫項目管道。如果想要保存抓取的items到j(luò)son文件中,推薦使用Feedexports
刪除重復(fù)項
假設(shè)在spider中提取到的item有重復(fù)的id,那么我們就可以在process_item函數(shù)中進行過濾
如:
from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.ids_seen = set() def process_item(self, item, spider): if item['id'] in self.ids_seen: raise DropItem("Duplicate item found: %s" % item) else: self.ids_seen.add(item['id']) return item
激活I(lǐng)temPipeline組件
在settings.py文件中,往ITEM_PIPELINES中添加項目管道的類名,就可以激活項目管道組件
如:
ITEM_PIPELINES = { 'myproject.pipeline.PricePipeline': 300, 'myproject.pipeline.JsonWriterPipeline': 800, }
The integer values you assign to classes in this setting determine the order they run in- items go through pipelines from order number low to high
整數(shù)值通常設(shè)置在0-1000之間
總結(jié)
以上就是本文關(guān)于Python:Scrapy框架中Item Pipeline組件使用詳解的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
解決Django no such table: django_session的問題
這篇文章主要介紹了解決Django no such table: django_session的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04python處理xls文件openpyxl基礎(chǔ)操作
這篇文章主要為大家介紹了python處理xls文件openpyxl基礎(chǔ)操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08卷積神經(jīng)網(wǎng)絡(luò)CharCNN實現(xiàn)中文情感分類任務(wù)
這篇文章主要為大家介紹了卷積神經(jīng)網(wǎng)絡(luò)CharCNN實現(xiàn)中文情感分類任務(wù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04