gpt4 book ai didi

python - 为什么 lxml 不去掉节标签?

转载 作者:行者123 更新时间:2023-12-01 04:52:08 24 4
gpt4 key购买 nike

我正在尝试使用 lxml 和 Python 解析一些 HTML。我想删除部分标签。 lxml 似乎能够删除我指定的所有其他标签,但不能删除部分标签。

例如

test_html = '<section> <header> Test header </header> <p> Test text </p> </section>'
to_parse_html = etree.fromstring(test_html)

etree.strip_tags(to_parse_html,'header')
etree.tostring(to_parse_html)

'<section> Test header <p> Test text </p> </section>'

etree.strip_tags(to_parse_html,'p')
etree.tostring(to_parse_html)
'<section> Test header Test text </section>'

etree.strip_tags(to_parse_html,'section')
etree.tostring(to_parse_html)
'<section> Test header Test text </section>'

为什么会这样?

最佳答案

Why is this the case?

事实并非如此。 documention说如下:

Note that this will not delete the element (or ElementTree root element) that you passed even if it matches. It will only treat its descendants.

所以:

>>> tree = etree.fromstring('<section> outer <section> inner </section> </section>')
>>> etree.strip_tags(tree, 'section')
>>> etree.tostring(tree)
'<section> outer inner </section>'

您看到的行为与<section>无关。标签,但事实上它恰好是代码片段的最外层标签。因此,您问题的实际答案是“因为它是这样实现的”。

要删除最外面的标签:是否可以更改创建 <section>...</section> 的代码去做这个?如果没有,则 ElementDepthFirstIterator 可能会成功:

>>> tree = etree.fromstring('<section> outer <section> inner </section> </section>')
>>> for val in etree.ElementDepthFirstIterator(tree, tag=None, inclusive=False):
... print(etree.tostring(val))

b'<section> inner </section> '

关于python - 为什么 lxml 不去掉节标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28195094/

24 4 0