2017-02-22 122 views
1

我试图在单独的MongoDB集合中存储单独的项目与pymongo和scrapy。Scrapy写入到多个MongoDB集合

我应该如何接近创造一个流水线 1)蜘蛛打开时开始pymongo连接的字典, 2)流程,并通过名称标识的项目, 3)并插入项目的收藏品之一在给定的请求内。

我不确定它是否可以写入scrapy中的多个集合。任何有识之士将不胜感激!

+0

不知道关于你的问题,你想相同的数据存储到2个数据库? – Umair

+0

解决了!感谢Umair – Chris

回答

1

我最初试图做一个蜘蛛可以写入不同项目的集合的字典对象。

经过一番研究,我在mongodb文档中遇到了“连接池”,并且意识到我需要使用1个连接创建连接到多个端点的dict对象,而不是多个集合。

class MongoDBPipeline(BaseItemExporter): 

#... 

    #item types for mongo to insert to correct collection 
    writeTypes = [ 
     'ent_pfrm', 'ent_prsn', 
     'ent_sctn', 'ent_meet', 
     'ent_venu', 'ent_affn' 
    ] 

#... 

    def open_spider(self, spider): 

     #Set db dict 
     self.database = dict([(name,connection[self.config['database']][name]) for name in self.writeTypes]) 

一旦项目被处理,得到的名称,检查字典,然后插入如果有匹配

def process_item(self, item, spider): 

    def item_type(item): 
     return type(item).__name__.replace('_Item','').lower() # Team_Item => team 

    item_name = item_type(item) 

    #check if the item matches one of the 'writeTypes' 
    if item_name in self.database.keys(): 
     dbcol = self.database[item_name] 
     dbcol.insert(item) 

    return item