gpt4 book ai didi

python - lxml 过滤子标签之间没有文本的 HTML 标签

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:24 25 4
gpt4 key购买 nike

我有一些这样的文件

....
<tag1>
<tag2>Foo</tag2>
<tag3>Bar</tag3>
</tag1>

<tag1>
<tag2>Foo</tag2>
<tag3>Bar</tag3>
Foo
</tag1>

<tag1>
<tag2>Foo</tag2>
Foo
<tag3>Bar</tag3>
</tag1>

<tag1>
Foo
</tag1>
....

我想过滤只有子标签的标签,即子标签之间没有一些文本。在上述情况下,它应该返回第一个 <tag1> .

我的代码最初是

from lxml import html

html_content = html.fromstring(content)
tag1 = html_content.xpath('//tag1')
tags = []
for tag in tag1:
exists = False
for child in tag.getchildren():
exists = exists or (len(child.tag) == 0)
if (not exists):
tags.append(tag)

但事实证明getchildren()不返回不在任何标记之间的文本。如何做到这一点?

最佳答案

使用 .tail attribute的标签:

for tag in tag1:
exists = False
for child in tag.getchildren():
exists = exists or not child.tail.strip()
if not exists:
tags.append(tag)

根据“只有子标签”的意思,这等同于:

for tag in tag1:
children = tag.getchildren()
no_extra_text = not any(child.tail.strip() for child in children)
if children and no_extra_text:
tags.append(tag)

这是一个更新,包括检查前导文本并在文本为 None 时删除错误(我认为它总是一个字符串):

for tag in tag1:
children = tag.getchildren()
no_extra_text = not any(child.tail and child.tail.strip() for child in children)
no_text = tag.text and not tag.text.strip()
if children and no_extra_text and no_text:
tags.append(tag)

关于python - lxml 过滤子标签之间没有文本的 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238232/

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