我有一个嵌套的JSON(API)webtie,我想解析它并将其保存到文件中(使用Scrapy framework)。在
我想访问给定元素的每个子元素,这些元素的格式如下
0 {…}
1 {…}
2 {…}
3 {…}
4 {…}
5 {…}
6 {…}
7 {…}
8 {…}
9 {…}
10 {…}
如果我展开元素0,我得到以下值,其中{…}将进一步扩展
^{pr2}$How does it look like in reality
如何连续访问每个元素,先是0,然后是1,然后是2。。。例如,总计为350,抓取值为
guid
rendered "https//:example.com"
并保存到项目。在
我所拥有的:
results = json.loads(response.body_as_unicode())
item = DataItem()
for var in results:
item['guid'] = results["guid"]
yield item
这样做失败了
TypeError: list indices must be integers, not str
我知道我可以用
item['guid'] = results[0]["guid"]
但这只给了我整个列表的[0]索引,我想遍历所有索引。如何在列表中传递索引号?在
将for循环中的
results["guid"]
替换为var["guid"]
:当您可以像
results[0]["guid"]
那样访问guid
时,这意味着您有一个字典列表,每个字典都包含名为guid
的键。在for循环中,使用results
(即list)而不是抛出TypeError
的var
(包含每次迭代中的每个字典),因为列表索引必须是整数而不是字符串(比如"guid"
)。在更新:如果您想保存每个
^{pr2}$var["guid"]
可以将它们保存在字典中,如下所示:现在
guid_holder
包含所有元素。在相关问题 更多 >
编程相关推荐