gpt4 book ai didi

Python ElementTree 检查节点/元素类型

转载 作者:行者123 更新时间:2023-12-01 06:15:11 25 4
gpt4 key购买 nike

我正在使用 ElementTree,无法确定子节点是否是文本。 childelement.text 似乎不起作用,因为即使在非文本节点的节点上它也会给出误报。

有什么建议吗?

示例

<tr>
<td><a href="sdas3">something for link</a></td>
<td>tttttk</td>
<td><a href="tyty">tyt for link</a></td>
</tr>

解析此 xml 文件后,我在 Python 中执行此操作:

for elem_main in container_trs: #elem_main is each tr
elem0 = elem_main.getchildren()[0] #td[0]
elem1 = elem_main.getchildren()[1] #td[1]

elem0 = elem_main.getchildren()[0]
print elem0.text

elem1 = elem_main.getchildren()[1]
print elem1.text

上面的代码没有输出elem0.text;它是空白的。我确实在输出中看到了 elem1.text(即 tttttk)。

更新2

我实际上正在构建一本字典。每个元素中的文本,以便我可以对 HTML 表进行排序。我如何获得这段代码中的 s ?

最佳答案

使用 getiterator 怎么样?迭代所有后代节点的方法:

import xml.etree.ElementTree as xee

content='''
<tr>
<td><a href="sdas3">something for link</a></td>
<td>tttttk</td>
<td><a href="tyty">tyt for link</a></td>
</tr>
'''

def text_content(node):
result=[]
for elem in node.getiterator():
text=elem.text
if text and text.strip():
result.append(text)
return result

container_trs=xee.fromstring(content)
adict={}
for elem in container_trs:
adict[elem]=text_content(elem)
print(adict)
# {<Element td at b767e52c>: ['tttttk'], <Element td at b767e58c>: ['tyt for link'], <Element td at b767e36c>: ['something for link']}

循环for elem_main in container_trs:迭代 cantainer_trs 的子级.

相比之下,循环 for elem_main in container_trs.getiterator():迭代器 container_trs它本身,以及它的 child 和孙子等。

关于Python ElementTree 检查节点/元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com