怎么删除html中的节点标签,在lxml中如何从节点中删除标签?

虽然从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}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值