2017-02-22 51 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