如何在scrapy中实现嵌套项?

时间:2012-06-25 06:46:40

标签: python json scrapy

我正在使用复杂的分层信息抓取一些数据,需要将结果导出到json。

我将这些项目定义为

class FamilyItem():
    name = Field()
    sons = Field()

class SonsItem():
    name = Field()
    grandsons = Field()

class GrandsonsItem():
    name = Field()
    age = Field()
    weight = Field()
    sex = Field()

当蜘蛛完成后,我将得到一个打印项目输出,如

{'name': 'Jenny',
   'sons': [
            {'name': u'S1',
             'grandsons': [
                   {'name': u'GS1',
                    'age': 18,
                    'weight': 50
                   },
                   {
                    'name':u'GS2',
                    'age': 19,
                    'weight':51}]
                   }]
}

但是当我运行scrapy crawl myscaper -o a.json时,它总是说结果“不是JSON可序列化的”。然后我将项目输出复制并粘贴到ipython控制台并使用json.dumps(),它工作正常。所以问题出在哪里?这是在推动我的坚果......

2 个答案:

答案 0 :(得分:26)

保存嵌套项目时,请确保将它们包装在对dict()的调用中,例如:

gs1 = GrandsonsItem()
gs1['name'] = 'GS1'
gs1['age'] = 18
gs1['weight'] = 50

gs2 = GrandsonsItem()
gs2['name'] = 'GS2'
gs2['age'] = 19
gs2['weight'] = 51

s1 = SonsItem()
s1['name'] = 'S1'
s1['grandsons'] = [dict(gs1), dict(gs2)]

jenny = FamilyItem()
jenny['name'] = 'Jenny'
jenny['sons'] = [dict(s1)]

答案 1 :(得分:2)

不确定是否有一种方法可以在类中运行嵌套项,但数组工作正常。你可以这样做:

grandson['name'] = 'Grandson'
grandson['age'] = 2
gransons.append(grandson)
son['name'] = 'Son'
sons['grandson'] = grandsons
sons.append(son)
item.name = 'Name'
item.son = sons