为了账号安全,请及时绑定邮箱和手机立即绑定

删除某个子节点后的子节点

删除某个子节点后的子节点

胡说叔叔 2021-07-18 20:19:55
我想删除<hr/>元素(包括<hr/>)下方的元素内的所有节点(包括文本)。例如,这个:<td class="one">    Some text    <a href="page1.html"/>    <br/>    Some more text    <br/>    <a href="page2.html"/>    <hr/>    Bottom text    <br/>    <a href="page3.html"/></td>应该变成:<td class="one">    Some text    <a href="page1.html"/>    <br/>    Some more text    <br/>    <a href="page2.html"/></td>我有这个 XPath 来查找下面的所有元素<hr/>:./node()[ preceding-sibling::hr[not(following-sibling::hr)] ]但我不知道如何删除这些元素。我试图这样做:xp = './node()[ preceding-sibling::hr[not(following-sibling::hr)] ]'els = self.xpath(xp, td_el)for el in els:    el.getparent().remove(el)但它不适用于文本节点。最好的方法是什么?谢谢。
查看完整描述

1 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

尝试使用以下代码删除节点:


from lxml import etree, html


source = """<td class="one">

    Some text

    <a href="page1.html"/>

    <br/>

    Some more text

    <br/>

    <a href="page2.html"/>

    <hr/>

    Bottom text

    <br/>

    <a href="page3.html"/>

</td>"""

html = html.fromstring(source)

parent = html.xpath('//td')[0]

redundant = html.xpath('//hr/preceding-sibling::*[1]/following-sibling::*')


for node in redundant:

    parent.remove(node)


print(etree.tostring(parent))

输出


<td class="one">

    Some text

    <a href="page1.html"/>

    <br/>

    Some more text

    <br/>

    <a href="page2.html"/>

</td>


查看完整回答
反对 回复 2021-07-27
  • 1 回答
  • 0 关注
  • 185 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号