本文共 838 字,大约阅读时间需要 2 分钟。
虽然从phlou得到的答案是可行的,但是有更简单的方法可以删除标签而不必删除标签的尾部。在
如果要删除特定元素,那么您要查找的LXML方法是drop_tree。在
从文件中:Drops the element and all its children. Unlike el.getparent().remove(el) this does not remove the tail text; with drop_tree the tail text is merged with the previous element.
如果要删除特定标记的所有实例,可以将lxml.etree.strip_elements或{}与{}一起使用。在Delete all elements with the provided tag names from a tree or
subtree. This will remove the elements and their entire subtree,
including all their attributes, text content and descendants. It
will also remove the tail text of the element unless you
explicitly set the with_tail keyword argument option to False.
所以,以原文中的例子为例:>>> from lxml.html import fragment_fromstring, tostring
>>>
>>> html = fragment_fromstring('TextText2')
>>> for bad in html.xpath('.//b'):
... bad.drop_tag()
>>> tostring(html)
'Text2'
或者
^{pr2}$
转载地址:http://qmiox.baihongyu.com/