Python–分解bs4.element.NavigableString(使用BeautifulSoup解析的xml)



有一个半解析的xml结果。我称之为semi是因为它有点管用,也有点不管用。这是由于原始文件为"半格式"。

我尝试过使用元素树进行解析,但效果更差,所以返回到使用BeautifulSoup进行解析。

我需要帮助得到孩子们的名字,下面是"Line"。

我有很多孩子,最高级的如下:

<Line> 
<ID>0b10-bd-59-ac-bac</ID>
<Type ref="cc-63-5c-bf-01"/>
<Base ref="8c-20-59-b7-eb"/>
<length multiplier="none" unit="m">28.536756216711005</length>
<b0ch multiplier="none" unit="S"/>
<bch multiplier="none" unit="S"/>
<r multiplier="none" unit="ohm">0.03361629882328556</r>
<r0 multiplier="none" unit="ohm">0.033624859850150575</r0>
<x multiplier="none" unit="ohm">0.008802762240586673</x>
<x0 multiplier="none" unit="ohm">1.1414702486684403E-05</x0>
</Line>

当我在"行"下面列出信息时,我得到:

[<ID>0b10-bd-59-ac-bac</ID>, <Type ref="cc-63-5c-bf-01"/>, <Base ref="8c-20-59-b7-eb"/>, <length multiplier="none" unit="m">28.536756216711005</length>, <b0ch multiplier="none" unit="S"/>, <bch multiplier="none" unit="S"/>, <r multiplier="none" unit="ohm">0.03361629882328556</r>, <r0 multiplier="none" unit="ohm">0.033624859850150575</r0>, <x multiplier="none" unit="ohm">0.008802762240586673</x>, <x0 multiplier="none" unit="ohm">1.1414702486684403E-05</x0>]

对于列表中的元素,我可以将bs4.element.NavigableString转换为字符串,然后根据需要对它们进行排序。

但当我试图获取信息的"父级"时,它会返回"子级"的整个第一个瞬间,与上面的代码相同,以,开头和结尾。

总的来说,我无法处理这么多信息。它不能作为一个整体转换为字符串。

循环浏览所有子项时,我不知道第一个子项的名称,也不知道下一个子项名称。

如何在不知道姓名或姓名长度的情况下提取这些信息?

Edit:看起来您正在尝试解析XML。也许你应该看看这个更简单的方法,而不是使用BeautifulSoup:https://www.edureka.co/blog/python-xml-parser-tutorial/

使用这种方法,你可以只做

import xml.etree.ElementTree as ET
data='''
<Line> 
<ID>0b10-bd-59-ac-bac</ID>
<Type ref="cc-63-5c-bf-01"/>
<Base ref="8c-20-59-b7-eb"/>
<length multiplier="none" unit="m">28.536756216711005</length>
<b0ch multiplier="none" unit="S"/>
<bch multiplier="none" unit="S"/>
<r multiplier="none" unit="ohm">0.03361629882328556</r>
<r0 multiplier="none" unit="ohm">0.033624859850150575</r0>
<x multiplier="none" unit="ohm">0.008802762240586673</x>
<x0 multiplier="none" unit="ohm">1.1414702486684403E-05</x0>
</Line>
'''
myroot = ET.fromstring(data)
print(myroot.tag)
> Line

print(myroot[0].tag)
> ID

for x in myroot:
print(x.tag, x.attrib, x.text)
> ID {} 0b10-bd-59-ac-bac
> Type {'ref': 'cc-63-5c-bf-01'} None
> Base {'ref': '8c-20-59-b7-eb'} None
> length {'multiplier': 'none', 'unit': 'm'} 28.536756216711005
> b0ch {'multiplier': 'none', 'unit': 'S'} None
> bch {'multiplier': 'none', 'unit': 'S'} None
> r {'multiplier': 'none', 'unit': 'ohm'} 0.03361629882328556
> r0 {'multiplier': 'none', 'unit': 'ohm'} 0.033624859850150575
> x {'multiplier': 'none', 'unit': 'ohm'} 0.008802762240586673
> x0 {'multiplier': 'none', 'unit': 'ohm'} 1.1414702486684403E-05

例如:

myroot[3].tag, myroot[3].attrib['unit'], myroot[3].text
> ('length', 'm', '28.536756216711005')

最新更新