【发布时间】:2020-01-30 22:36:58
【问题描述】:
我需要在Python3 中使用BeautifulSoup 解析XML 文档,以从属性中获取所有值——由空元素(嵌套与否)相互分隔。一次获取 所有 值很容易,但我需要将它们分开。
请参阅下面的 MWE:我需要 c-元素中的所有 val-值,由 lb- 或 pb-元素分隔。现在的列表输出是:[1, 2, 3, 4, 5, 6, 7, 8],但我需要一个类似[[1, 2], [3,4], [5, 6], [7, 8]](或dict)的列表。
我认为问题在于,我无法关联下一个空元素(它不是sibling,也不是next_element)。
感谢您的帮助!
MWE-XML-示例:“file.xml”
<text>
<nested>
<c val="1">A</c>
<c val="2">B</c>
</nested>
<lb/>
<nested>
<nested>
<c val="3">C</c>
<c val="4">D</c>
<lb/>
<pb/>
<c val="5">E</c>
<c val="6">F</c>
<c type="empty"> </c>
</nested>
</nested>
<lb/>
<c val="7">G</c>
<c val="8">H</c>
</text>
MWE-python3-示例
from bs4 import BeautifulSoup
with open("file.xml", "r", encoding="utf-8") as fh:
soup = BeautifulSoup(fh.read(), "lxml-xml")
listoflists = list()
val_list = list()
for c in soup.find_all("c"):
if not "val" in c.attrs:
continue
else:
val_list.append( int(c["val"]) )
if c.next_sibling == (soup.lb or soup.pb): # <-- not working?
listoflists.append(val_list)
continue
print(val_list)
print(listoflists)
【问题讨论】:
标签: python xml beautifulsoup