0

我正在使用Scrapy抓取和抓取网站,并使用来自scrapy-mongodb的项目管道将项目保存到MongoDB。这样做如何将不同类型的项目保存到不同的集合中?例如,要收集的类型项目和要收集的类型项目?如果使用项目管道无法做到这一点,您能想到另一种解决方案吗?PersonItempersonsBookItembooks

4

2 回答 2

1

您还可以为每种类型创建两个不同的管道:在pipelines.py

class PersonPipeline(object):
    def __init__(self):
        connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
        db = connection[settings['MONGODB_DB']]
        self.collection = db[settings['MONGODB_PERSON_COLLECTION']] # use the person collection

    def process_item(self, item, spider):
        if not isinstance(item,PersonItem):
            return item # return the item to let other pipeline to handle it
        self.collection.insert(dict(item))

class BookPipeline(object):
    def __init__(self):
        connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
        db = connection[settings['MONGODB_DB']]
        self.collection = db[settings['MONGODB_BOOK_COLLECTION']] # use the book collection

    def process_item(self, item, spider):
        if not isinstance(item,PersonItem):
            return item # return the item to let other pipeline to handle it
        self.collection.insert(dict(item))

settings.py

ITEM_PIPELINES = { # declare the handle sequence
    'myproject.pipelines.PersonPipeline':100,
    'myproject.pipelines.BookPipeline':200,
}
MONGODB_SERVER = "localhost"
MONGODB_PORT = 27017
MONGODB_DB = "MyDB" # db name
MONGODB_PLACE_COLLECTION = "persons" # collection name
MONGODB_LIST_COLLECTION = "books"

当一个项目返回时,PersonPipeline将首先处理它。如果项目不是PersonItem类型,那么它将返回到下一个管道,BookPipeline在这种情况下是。

于 2014-06-10T00:51:03.400 回答
0

当然,在(子类)MongoDBPipeline管道中是可能的。

以下内容未经测试,但一种选择是更改self.collection为集合的字典,将项目类型映射到 Mongo 集合。

class CustomMongoDBPipeleine(MongoDBPipeline):

  def __init__(self, settings):
    ...
    mapping = {
        PersonItem: 'persons',
        BookItem: 'books',
    }
    self.collection = {}
    for itype, collection_name in mapping.items():
        self.collection[itype] = database[collection_name]

映射可以来自配置,并直接使用项目类型类名称而不是项目类。

并使用类似的东西:

    insert_item(self, item, spider):
        ...
        self.collection.get(type(item)).insert(item, continue_on_error=True)
        ...
于 2013-10-29T10:34:34.063 回答