我在使用的项目管道爬取和刮取Scrapy网站并将项目保存到MongoDB。这样做如何将不同类型的项目保存到不同的集合?像例如PersonItem
类型的项目收集persons
和BookItem
类型的项目收集books
?如果这不可能使用物品管道,你能想到另一个解决方案吗?根据项目类型在mongodb中使用不同的集合
0
A
回答
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)
...
0
您还可以创建两个不同的管道对每一种类型:在settings.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))
:在pipelines.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
。
相关问题
- 1. 根据集合中的子类类型从集合中选择项目
- 2. 比较集合不同项目类型
- 3. 在复合集合中插入不同的项目类型
- 4. LINQ来选择不同类型的集合中的项目
- 5. MongoDb在集合中选择不同的对象类型
- 6. $ project MongoDB聚合中的不同项目
- 7. MongoDB - 重复项目集合
- 8. 在mongodb中使用相同的集合扩展回送模型?
- 9. Mongodb不将项目插入集合
- 10. 序列化集合项时使用类型的根名称
- 11. 在mongodb数据库中更改集合中字段的类型
- 12. Java:根据子类型订购集合
- 13. 在VB.Net项目中使用强类型数据集
- 14. MongoDB:从子集合中删除项目
- 15. Scrapy:如何将不同蜘蛛的项目写入不同的MongoDB集合?
- 16. 哪个列表/集合类型最适合在WCF数据合同中使用?
- 17. 将新集合项目推送到不同类别的GridView中
- 18. 覆盖使用不同的返回类型(泛型集合)
- 19. 根据数据类型获取不同的结果集
- 20. 从mongodb中读取不同于集合实际类的类
- 21. yii mongodb集合中的不同值
- 22. 在不同项目中使用共享数据集
- 23. 在MongoDB中找不到数据集合
- 24. NodeJS/MongoDB中用于集合的不同数据库
- 25. 如何根据日期使用不同的日期值集合
- 26. AutoMapper可以根据类型将集合项目复制到特定的集合吗?
- 27. set_intersection两种不同类型的集合
- 28. MongoDB中字段的数据类型集合
- 29. PostgreSQL的:计数根据不同的项目在不同的列
- 30. 使用两个集合类型参数查找项目索引