2013-04-22 102 views
2

我創建了一個新的蜘蛛來抓取網站。 這種履帶獲得網站清單當然每個視頻遊戲,併爲它創建一個對象:Scrapy動態創建對象+ json導出

class gameInfos(Item): 
    title = Field() 
    desc = Field() 
    kind = Field() 

每場比賽,本網站包含的經銷商變量列表。我得到的每一個經銷商在對象:

class buyInfos(Item): 
    name = Field() 
    address = Field() 
    price = Field() 

現在,我的問題:

我希望把buyInfos對象(S)內gameInfos對象和我的JSON文件如下:

[ 
    { 
    "title": "BF3", 
    "desc": "a beautiful game", 
    "kind" : "FPS", 
    "buy" : 
      [ 
       {name : "cdiscount", "address" : "example", "price" : "45 €"}, 
       {name : "amazon", "address" : "example amazon", "price" : "40 €"}, 
       //... other resellers 
      ] 
    }, 
    { 
    "title": "COD 42", 
    "desc": "a game", 
    "kind" : "FPS", 
    "buy" : 
    }, 
    //... other games 
] 

所以我試圖在我的主要對象中創建一個對象。它的工作,但最後,我只有一個對象來填充,而我想在我的主要對象內創建一些對象。

感謝您的幫助

回答

1

解決辦法很簡單。創建一個對象:

class GameInfo(Item): 
    title = Field() 
    desc = Field() 
    kind = Field() 
    listeBuys = Field() 

然後,在你的蜘蛛,實例的GameInfo:

gameInfo = GameInfo() 

然後,實例爲所需字段Python列表:

gameInfo['listeBuys'] = [] 

最後,添加你想要的:

gameInfo['listeBuys'].append(asyouwant) 

感謝dm03514的幫助!

1

Scrapy Field類是dict一個子類。如果您想讓其中一個字段能夠包含Item列表,我相信您可以創建一個List字段。

class ListField(list): 
    pass 

class GameInfo(Item): 
    title = Field() 
    desc = Field() 
    kind = Field() 
    buys = ListField() 

現在在你的蜘蛛,你可以創建gameInfos,這將是能夠包含所有相關buyInfos

game_info = GameInfo() 
# create your buy info and append to game info 
game_info['buys'].append(new_buy_info) 
+0

感謝您的回答,但我有一個問題。 我創建了「ListField」,就像你我在主對象中添加了一個字段「infos = ListField()」。

然後,在我的蜘蛛:我創建我的主要對象(game_info = GameInfo())和我的子對象。
後,我嘗試:
game_info.append(new_buy_info)
但錯誤傳來=>

'game_info.append(子對象) 文件「/usr/lib/python2.7/site-packages/scrapy/ item.py「,第64行,在__getattr__ raise AttributeError(name) exceptions.AttributeError:append' – user2240632 2013-04-22 13:59:32

+0

@ user2240632對不起固定示例 – dm03514 2013-04-22 14:01:49

+0

我得到一個錯誤:'File」/root/mycrawler/mycrawler/spiders/jiwire.py 「,第107行,在parse_hotspot game_info [」buys「]。append(」test「) 文件」/usr/lib/python2.7/site-packages/scrapy/item。py「,第49行,在__getitem__ return self._values [key] exceptions.KeyError:'buys'' – user2240632 2013-04-22 16:09:52