python - 删除某个子节点之后的子节点

标签 python xpath lxml

我想删除元素内 <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)

但它不适用于文本节点。

最好的方法是什么? 谢谢。

最佳答案

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

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>

关于python - 删除某个子节点之后的子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52931823/

相关文章:

python - 如何在 lxml xpath 中使用正则表达式?

python - 使用 lxml tostring() 获取原始字符串

python - 使用动态表用 pandas 解析 SQL 参数标记

python - 在C++中模拟python的 "in"

python - 连接云存储和云功能

xml - 使用 xsl 模板参数作为选择中的节点(即元素的值)

选择 Selenium 中已知元素的父元素

Python lxml.etree 保留实体引用

python - 使用 BeautifulSoup 进行网页抓取,得到空列表

xml - XSLT count() 包括引用节点比较