Scrapy - 專案管道



描述

專案管道 (Item Pipeline) 是一種處理爬取到的資料項的方法。當一個數據項被髮送到專案管道時,它已經由爬蟲爬取,並透過多個依次執行的元件進行處理。

每當接收到一個數據項,管道會決定以下其中一種操作:

  • 繼續處理資料項。
  • 從管道中丟棄資料項。
  • 停止處理資料項。

專案管道通常用於以下目的:

  • 將爬取的資料項儲存到資料庫。
  • 如果接收到重複的資料項,則會丟棄重複項。
  • 檢查資料項是否包含目標欄位。
  • 清除HTML資料。

語法

您可以使用以下方法編寫專案管道:

process_item(self, item, spider) 

上述方法包含以下引數:

  • Item (資料項物件或字典) - 指定爬取到的資料項。
  • spider (爬蟲物件) - 爬取該資料項的爬蟲。

您可以使用下表中列出的其他方法:

序號 方法 & 描述 引數
1

open_spider(self, spider)

在爬蟲開啟時呼叫。

spider (爬蟲物件) - 指的是被開啟的爬蟲。

2

close_spider(self, spider)

在爬蟲關閉時呼叫。

spider (爬蟲物件) - 指的是被關閉的爬蟲。

3

from_crawler(cls, crawler)

透過爬蟲物件,管道可以訪問Scrapy的核心元件,例如訊號和設定。

crawler (爬蟲物件) - 指的是使用此管道的爬蟲。

示例

以下是專案管道在不同場景中的示例。

丟棄沒有標籤的資料項

在下面的程式碼中,管道會為那些不包含增值稅 (excludes_vat 屬性) 的資料項平衡 (price) 屬性,並忽略那些沒有價格標籤的資料項:

from Scrapy.exceptions import DropItem  
class PricePipeline(object): 
   vat = 2.25 

   def process_item(self, item, spider): 
      if item['price']: 
         if item['excludes_vat']: 
            item['price'] = item['price'] * self.vat 
            return item 
         else: 
            raise DropItem("Missing price in %s" % item) 

將資料項寫入 JSON 檔案

下面的程式碼會將所有爬蟲爬取到的資料項儲存到單個 items.jl 檔案中,該檔案每行包含一個以 JSON 格式序列化的資料項。程式碼中使用了 JsonWriterPipeline 類來演示如何編寫專案管道:

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

將資料項寫入 MongoDB

您可以在 Scrapy 設定中指定 MongoDB 地址和資料庫名稱,MongoDB 集合可以根據資料項類命名。下面的程式碼描述瞭如何使用 from_crawler() 方法正確收集資源:

import pymongo  

class MongoPipeline(object):  
   collection_name = 'Scrapy_list' 

   def __init__(self, mongo_uri, mongo_db): 
      self.mongo_uri = mongo_uri 
      self.mongo_db = mongo_db 

   @classmethod 
   def from_crawler(cls, crawler): 
      return cls( 
         mongo_uri = crawler.settings.get('MONGO_URI'), 
         mongo_db = crawler.settings.get('MONGO_DB', 'lists') 
      ) 
  
   def open_spider(self, spider): 
      self.client = pymongo.MongoClient(self.mongo_uri) 
      self.db = self.client[self.mongo_db] 

   def close_spider(self, spider): 
      self.client.close() 

   def process_item(self, item, spider): 
      self.db[self.collection_name].insert(dict(item)) 
      return item

重複項過濾

過濾器會檢查重複的資料項,並丟棄已處理的資料項。在下面的程式碼中,我們為資料項使用了唯一的 ID,但爬蟲返回許多具有相同 ID 的資料項:

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("Repeated items found: %s" % item) 
      else: 
         self.ids_seen.add(item['id']) 
         return item

啟用專案管道

您可以透過將專案管道的類新增到 ITEM_PIPELINES 設定中來啟用它,如下面的程式碼所示。您可以為類分配整數來指定它們的執行順序(順序可以是從較低值到較高值的類),值範圍為 0-1000。

ITEM_PIPELINES = {
   'myproject.pipelines.PricePipeline': 100,
   'myproject.pipelines.JsonWriterPipeline': 600,
}
廣告
© . All rights reserved.