- 在
pipelines.py
中寫入MongoDBPipeline
,代碼如下:
from scrapy import Item
import pymongo
class MongoDBPipeline(object):
"""
將item寫入MongoDB
"""
@classmethod
def from_crawler(cls, crawler):
cls.DB_URL = crawler.settings.get('MONGO_DB_URI', 'mongodb://localhost:27017')
cls.DB_NAME = crawler.settings.get('MONGO_DB_NAME', 'scrapy_data')
return cls()
def open_spider(self, spider):
self.client = pymongo.MongoClient(self.DB_URL)
self.db = self.client[self.DB_NAME]
def close_spider(self, spider):
self.client.close()
def process_item(self, item, spider):
collection = self.db[spider.name]
post = dict(item) if isinstance(item, Item) else item
collection.insert_one(post)
return item
- 增加類方法from_crawler(cls, crawler),替代在類屬性中定義DB_URL和DB_NAME迹栓。
- 如果一個(gè)Item Pipeline定義了from_cwawler方法掉分,Scrapy就會(huì)調(diào)用該方法來創(chuàng)建Item Pipeline對象,該方法有兩個(gè)參數(shù)
- ?cls Item Pipeline類的對象(這里為MongoDBPipeline類對象)
- ?crawler Crawler是Scrapy中的一個(gè)核心對象克伊,可以通過crawler的settings屬性訪問該配置文件酥郭。
- 在from_crawler方法中,讀取配置文件中的MONGO_DB_URL和MONGO_DB_NAME(不存在則使用默認(rèn)值)愿吹,賦給cls的屬性不从,即MongoDBPipeline類屬性。
- 在Spider整個(gè)爬取過程中犁跪,數(shù)據(jù)庫的連接和關(guān)閉操作只需要進(jìn)行一次椿息,應(yīng)在開始處理數(shù)據(jù)之前連接數(shù)據(jù)庫,并在處理完所有數(shù)據(jù)之后關(guān)閉數(shù)據(jù)庫坷衍。因此實(shí)現(xiàn)以下兩個(gè)方法(在Scrapy打開和關(guān)閉時(shí)被調(diào)用):
- ?open_spider(spider)
- ?close_spider(spider)
分別在open_spider和close_spider方法中實(shí)現(xiàn)數(shù)據(jù)庫的連接與關(guān)閉撵颊。
- 在process_item中實(shí)現(xiàn)MongoDB數(shù)據(jù)庫的寫入操作,使用self.db和spider.name獲取一個(gè)集合(collection)惫叛,然后將數(shù)據(jù)插入該集合倡勇,集合對象的insert_one方法需傳入一個(gè)字典對象(不能傳入Item對象),因此在調(diào)用前先對item的類型進(jìn)行判斷,如果item是Item對象妻熊,就將其轉(zhuǎn)換為字典夸浅。
- 在配置文件
settings.py
中對所要使用的數(shù)據(jù)庫進(jìn)行設(shè)置:
MONGO_DB_URI = 'mongodb://localhost:27017'
MONGO_DB_NAME = 'scrapy_data'
- 運(yùn)行爬蟲查看。
若沒有MongoDB扔役,可查看此文章:http://www.reibang.com/p/1ab7f03f4e5a
運(yùn)行Docker
命令進(jìn)入MongoDB:
docker exec -it mongo_db mongo
>use scrapy_data
>db.books.count()
1000
>db.books.find()
...
即可查看數(shù)據(jù)庫中的結(jié)果