iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
1
AI & Data

爬蟲在手、資料我有 - 30 天 Scrapy 爬蟲實戰系列 第 29

【Day 28】Item Pipelines 應用 - 儲存資料到 MongoDB

延續昨天的主題,今天要建立一個 Pipeline 元件,用來將爬到的資料存到 MongoDB 中。

建立 Pipeline 元件

在專案目錄的 pipelines.py 檔案中新增一個 MongoPipeline 類別:

import pymongo

class MongoPipeline(object):
    collection_name = 'article'

    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

其中這兩行代表從 Scrapy 設定中取得對應的參數值:

mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')

同時要在專案目錄的 settings.py 檔案中加入這兩個設定:

MONGO_URI = 'mongodb://localhost:27017/'
MONGO_DATABASE = 'ithome2019'

將元件加入 Pipeline 執行序列

最後要在 settings.py 檔案中把剛剛建立的 Pipeline 元件加入執行序列中,要注意指定的順序值要比昨天的 ithome_crawlers.pipelines.IthomeCrawlersPipeline 大,因為存進資料庫的應該是過濾後的結果。

ITEM_PIPELINES = {
    'ithome_crawlers.pipelines.IthomeCrawlersPipeline': 300,
    'ithome_crawlers.pipelines.MongoPipeline': 400,
}

執行爬蟲

最後執行 scrapy crawl ithome 指令來執行爬蟲,可以在啟動的 log 中看到元件已經被加入 Pipeline 中。

https://ithelp.ithome.com.tw/upload/images/20191013/20107875dCF6hbxZc3.png

參考資料


上一篇
【Day 27】在 Scrapy 中處理爬取結果 - Item Pipelines
下一篇
【Day 29】在 Scrapy 中處理請求和回應 - Downloader Middlewares
系列文
爬蟲在手、資料我有 - 30 天 Scrapy 爬蟲實戰33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言