【发布时间】:2021-11-17 14:04:48
【问题描述】:
所以我有这个 XML 文件模型:
xml="""
<fruits>
<fruit>
<name>apple</name>
<types>
<type>
<color>red</color>
<taste>sweet</taste>
<size>big</size>
<description>Nice, round, sweet red apple</description>
</type>
<type>
<color>green</color>
<taste>sour</taste>
<size>medium</size>
<description>Small, sour, green apple</description>
</type>
</types>
</fruit>
<fruit>
<name>Banana</name>
<types>
<type>
<color>yellow</color>
<taste>sweet</taste>
<size>small</size>
<description>Good for banana-smoothies only</description>
</type>
<type>
<color>green</color>
<taste>Bitter</taste>
<size>big</size>
<description>Not quite ripe yet</description>
</type>
</types>
</fruit>
</fruits>
"""
#</editor-fold>
我正在尝试使用此代码:
from bs4 import BeautifulSoup
soup=BeautifulSoup(xml, 'lxml')
fruits=soup.findAll("fruit", recursive=False)
print(fruits)
type=soup.findAll("type")
list=[]
name=soup.findAll("name")
for nameid in range(len(name)):
list+=name[nameid]
for id in range(len(type)):
list+=(soup.findAll("color")[id].string)
list+=(soup.findAll("taste")[id].string)
list+=(soup.findAll("size")[id].string)
list+=(soup.findAll("description")[id].string)
list+=("""</tr>""")
#list.append("<td>"+soup.findAll("description")[id].string+"</td>")
#list.append("</tr>")
if list:
list="".join(list)
我无法找到一种方法来列出属性(的孩子),并在表格中列出名称。到目前为止,我尝试的所有操作最终都显示了名称,但是当它碰到香蕉时,它要么只显示苹果的属性,要么显示苹果和香蕉的属性。
我只是在 Python 中通过 BeautifulSoup+lxml 使用 for 循环。任何帮助表示赞赏!
【问题讨论】:
-
请阅读How to Ask并以minimal reproducible example的形式向我们展示您的尝试。
-
您尝试从 xml 中提取的信息是什么?使用您尝试构建的数据结构更新帖子。
标签: python xml beautifulsoup