【发布时间】:2016-12-18 14:37:22
【问题描述】:
我正在使用 beautifulsoup 来获取 XML 数据并将其放入一个字典数组中。但是,它没有按预期工作。相同的 dict 只是被添加到列表中。如何在嵌套 for 循环的正确阶段将正确的 dict 添加到列表中?
打印出来的列表应该如下所示:
[OrderedDict([('name', ‘dogs’), ('type', ‘housed’), ('value', ‘123’)]),
OrderedDict([('name', ‘cats’), ('type', ‘wild’), ('value', ‘456’)]),
OrderedDict([('name', ‘mice’), ('type', ‘housed’), ('value', ‘789’)])]
将它放在字典而不是列表中更好吗?
Here is the XML:
<window>
<window class="Obj" name="ray" type="housed">
<animal name="dogs", value = "123" />
<species name="sdogs", value = "s123" />
</window>
<window class="Obj" name="james" type="wild">
<animal name="cats", type="wild", value = "456" />
<species name="scats", type="swild", value = "s456" />
</window>
<window class="Obj" name="bob" type="housed">
<animal name="mice", value = "789" />
<species name="smice", value = "s789" />
</window>
</window>
这是代码(抱歉,如果有一些错误,我可以纠正它们,因为这是一个更大的代码示例):
import sys
import pprint
from bs4 import BeautifulSoup as bs
from collections import OrderedDict
soup = bs(open("test.xml"),"lxml")
dicty = OrderedDict()
listy = [];
Objs=soup.findAll('window',{"class":"Obj"})
#print Objs
for Obj in Objs:
Objarr = OrderedDict() #### move this down
#I want to add data to the array here:
#print Obj
for child in Obj.children:
Objarr.update({"namesss" : Obj['name']})
if child.name is not None:
if child.name == "species":
print Obj['name']
print child['value']
#Also, adding data to the array here:
Objarr.update({"name" : Obj['name']})
Objarr.update({"type" : Obj['type']})
Objarr.update({"value": child['name']})
listy.append(Objarr) #### dedent this
pprint.pprint(listy)
【问题讨论】:
-
请添加一些
Objs内容的示例以及预期的listy。 -
是的,现在这样做:)
-
hist ettanany ive 添加了返回的列表对象。
-
您还需要添加一些
Objs内容的示例。 -
touche,我看到了那个请求,现在就这样做
标签: python list dictionary beautifulsoup