アイテム・パイプライン¶
アイテムがスパイダーによってスクレイプされた後、アイテムはアイテム・パイプラインに送信され、アイテム・パイプラインは順次実行される複数のコンポーネントを介してアイテムを処理します。
各アイテム・パイプライン・コンポーネント(アイテム・パイプラインとも呼ばれる)は、単純なメソッドを実装するPythonクラスです。 それらはアイテムを受け取り、それに対してアクションを実行します。また、そのアイテムがパイプラインで処理を継続されるか、そのアイテムをドロップして処理しなくなくなるかを決定します。
アイテムパイプラインの一般的な用途は次のとおりです:
HTMLデータの洗浄(cleansing)
スクレイプしたグデータの検証(アイテムに特定のフィールドが含まれていることを確認)
重複のチェック(そして重複分をドロップする)
スクレイプされたアイテムをデータベースに保存する
あなた独自のアイテム・パイプラインを書く¶
各アイテム・パイプライン・コンポーネントは、Pythonクラスであり、次のメソッドを実装する必要があります:
-
process_item
(self, item, spider)¶ このメソッドは、すべてのアイテム・パイプライン・コンポーネントに対して呼び出されます。
process_item()
は、データの辞書を返す、あるいはItem
(または任意の子孫クラス)オブジェクトを返す、あるいは Twisted Deferred を返す、あるいはDropItem
例外を発生させる、のいずれかを行う必要があります。ドロップしたアイテムは、それ以降のパイプライン・コンポーネントにでは処理しません。
さらに、以下のメソッドも実装できます:
-
open_spider
(self, spider)¶ このメソッドは、スパイダーがオープンされたときに呼び出されます。
- パラメータ
spider (
Spider
object) -- オープンされたスパイダー
アイテム・パイプライン例¶
価格の検証と価格のないアイテムのドロップ¶
VAT(訳注:付加価値税)を含まないアイテムの価格( price_excludes_vat
属性)を調整し、価格を含まないアイテムをドロップする、次の仮想パイプラインを見てみましょう:
from scrapy.exceptions import DropItem
class PricePipeline(object):
vat_factor = 1.15
def process_item(self, item, spider):
if item.get('price'):
if item.get('price_excludes_vat'):
item['price'] = item['price'] * self.vat_factor
return item
else:
raise DropItem("Missing price in %s" % item)
JSONファイルにアイテムを書き込む¶
次のパイプラインは、(すべてのスパイダーからの)すべてのスクレイプされたアイテムを、JSON形式でシリアル化された行ごとに1つのアイテムを含む単一の items.jl
ファイルに保存します:
import json
class JsonWriterPipeline(object):
def open_spider(self, spider):
self.file = open('items.jl', 'w')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
注釈
JsonWriterPipelineの目的は、アイテム・パイプラインの記述方法を紹介することだけです。すべてのスクレイプ・アイテムをJSONファイルに保存する場合は、 フィード・エクスポート を使用する必要があります。
MongoDBにアイテムを書き込む¶
この例では、私たちは pymongo を使用してMongoDB にアイテムを書き込みます。MongoDBアドレスとデータベース名は、Scrapy設定で指定します。MongoDBコレクションは、アイテム・クラスに基づいて名前が付けられます。
この例の主なポイントは、 from_crawler()
メソッドの使用方法と、リソースを適切にクリーンアップする方法を示すことです:
import pymongo
class MongoPipeline(object):
collection_name = 'scrapy_items'
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_DATABASE', 'items')
)
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_one(dict(item))
return item
アイテムのスクリーンショットをとる¶
このデモンストレーションは、 process_item()
メソッドから Deferred を返す方法を示しています。 Splash を使用して、アイテムのURLのスクリーンショットをレンダリングします。 パイプラインは、ローカルで実行されている Splash のインスタンスにリクエストを行います。 リクエストがダウンロードされ、Deferredコールバックが起動した後、アイテムをファイルに保存し、ファイル名をアイテムに追加します。
import scrapy
import hashlib
from urllib.parse import quote
class ScreenshotPipeline(object):
"""Pipeline that uses Splash to render screenshot of
every Scrapy item."""
SPLASH_URL = "http://localhost:8050/render.png?url={}"
def process_item(self, item, spider):
encoded_item_url = quote(item["url"])
screenshot_url = self.SPLASH_URL.format(encoded_item_url)
request = scrapy.Request(screenshot_url)
dfd = spider.crawler.engine.download(request, spider)
dfd.addBoth(self.return_item, item)
return dfd
def return_item(self, response, item):
if response.status != 200:
# Error happened, return item.
return item
# Save screenshot to file, filename will be hash of url.
url = item["url"]
url_hash = hashlib.md5(url.encode("utf8")).hexdigest()
filename = "{}.png".format(url_hash)
with open(filename, "wb") as f:
f.write(response.body)
# Store filename in item.
item["screenshot_filename"] = filename
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("Duplicate item found: %s" % item)
else:
self.ids_seen.add(item['id'])
return item
アイテム・パイプライン・コンポーネントのアクティブ化¶
アイテム・パイプライン・コンポーネントをアクティブにするには、次の例のように、そのクラスを ITEM_PIPELINES
設定に追加する必要があります:
ITEM_PIPELINES = {
'myproject.pipelines.PricePipeline': 300,
'myproject.pipelines.JsonWriterPipeline': 800,
}
あなたがこの設定でクラスに割り当てる整数値は、それらが実行される順序を決定します。項目は、低い値のクラスから高い値のクラスへと通過します。 これらの数値は0〜1000の範囲で定義するのが慣例です。