欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python:Scrapy框架中Item Pipeline組件使用詳解

 更新時(shí)間:2017年12月27日 09:26:47   作者:曾是土木人  
這篇文章主要介紹了Python:Scrapy框架中Item Pipeline組件使用詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下

Item Pipeline簡介

Item管道的主要責(zé)任是負(fù)責(zé)處理有蜘蛛從網(wǎng)頁中抽取的Item,他的主要任務(wù)是清晰、驗(yàn)證和存儲數(shù)據(jù)。
當(dāng)頁面被蜘蛛解析后,將被發(fā)送到Item管道,并經(jīng)過幾個(gè)特定的次序處理數(shù)據(jù)。
每個(gè)Item管道的組件都是有一個(gè)簡單的方法組成的Python類。
他們獲取了Item并執(zhí)行他們的方法,同時(shí)他們還需要確定的是是否需要在Item管道中繼續(xù)執(zhí)行下一步或是直接丟棄掉不處理。

Item管道通常執(zhí)行的過程有

清理HTML數(shù)據(jù)
驗(yàn)證解析到的數(shù)據(jù)(檢查Item是否包含必要的字段)
檢查是否是重復(fù)數(shù)據(jù)(如果重復(fù)就刪除)
將解析到的數(shù)據(jù)存儲到數(shù)據(jù)庫中

編寫自己的Item Pipeline

編寫item管道其實(shí)是很容易的。
每個(gè)Item管道的組件都是由一個(gè)簡單的方法組成的Python類:

process_item(item, spider)

每一個(gè)item管道組件都會調(diào)用該方法,并且必須返回一個(gè)item對象實(shí)例或raise DropItem異常。
被丟掉的item將不會在管道組件進(jìn)行執(zhí)行
此外,我們也可以在類中實(shí)現(xiàn)以下方法

open_spider(spider)

當(dāng)spider執(zhí)行的時(shí)候?qū)⒄{(diào)用該方法

close_spider(spider)

當(dāng)spider關(guān)閉的時(shí)候?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(增值稅)

以上代碼可以過濾那些沒有價(jià)格的產(chǎn)品,并且對那些不包括增值稅產(chǎn)品的價(jià)格進(jìn)行調(diào)整

將抓取的items以json格式保存到文件中

從spider抓取到的items將被序列化為json格式,并且以每行一個(gè)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的目的是介紹如何編寫項(xiàng)目管道。如果想要保存抓取的items到j(luò)son文件中,推薦使用Feedexports

刪除重復(fù)項(xiàng)

假設(shè)在spider中提取到的item有重復(fù)的id,那么我們就可以在process_item函數(shù)中進(jìn)行過濾

如:

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中添加項(xiàng)目管道的類名,就可以激活項(xiàng)目管道組件

如:

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ù)參閱本站:

Python使用Scrapy保存控制臺信息到文本解析

Python爬蟲實(shí)例爬取網(wǎng)站搞笑段子

Python爬蟲獲取整個(gè)站點(diǎn)中的所有外部鏈接代碼示例

如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

相關(guān)文章

最新評論