Python lxml etree 从元素中移除尾部
Python lxml etree remove tail from element
我有一个包含 <p>
元素和尾部的元素。
例如:
<p>Content that I want to keep</p>content that I want removed
我注意到需要删除的内容在尾部,我认为有一种简单的方法可以使用 etree 从元素中删除尾部。
我怎样才能做到这一点?
经过几个小时的努力,我终于找到了答案。 (当然是在发布问题之后)
我只是将尾部设置为None:
element = root.xpath("path/to/element")
element[0].tail = None
string = tostring(element[0])
并且有效。
使用 lxml 包中的 elementsoup:
#!/usr/bin/env python
from lxml.html.soupparser import fromstring
s = """<p>Content that I want to keep</p>content that I want removed"""
print fromstring(s).find('.//p').text
老问题,但为了其他人寻找答案的利益,如果目标是"remove tail to call etree.tostring()",那么你不需要修改树:
https://lxml.de/api/lxml.etree-module.html#tostring
string = tostring(element[0], with_tail=False)
我有一个包含 <p>
元素和尾部的元素。
例如:
<p>Content that I want to keep</p>content that I want removed
我注意到需要删除的内容在尾部,我认为有一种简单的方法可以使用 etree 从元素中删除尾部。
我怎样才能做到这一点?
经过几个小时的努力,我终于找到了答案。 (当然是在发布问题之后)
我只是将尾部设置为None:
element = root.xpath("path/to/element")
element[0].tail = None
string = tostring(element[0])
并且有效。
使用 lxml 包中的 elementsoup:
#!/usr/bin/env python
from lxml.html.soupparser import fromstring
s = """<p>Content that I want to keep</p>content that I want removed"""
print fromstring(s).find('.//p').text
老问题,但为了其他人寻找答案的利益,如果目标是"remove tail to call etree.tostring()",那么你不需要修改树:
https://lxml.de/api/lxml.etree-module.html#tostring
string = tostring(element[0], with_tail=False)