python - 删除某个子节点后的子节点
问题描述
我想删除元素(包括 )下方的<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>
推荐阅读
- javascript - Leaflet _ ReactJS - 在哪里可以找到 invalidateSize 属性?
- java - “没有为 java.util.Optional 注册映射器”使用 JDBI v2 和 java.util.Optional
- python - 如何修复 NoneType 对象不可调用错误?
- python - Python:将点分配给 bin 的更快或无循环方式?
- sql - 有没有办法用索引加速这个多表查询?
- java - 为列表属性创建 PATCH 端点
- python - 使用 Pandas 将 yyyy-mm-ddThh:mm:ss-07:00 更改为太平洋时间,不显示时区
- angular - 如何对表的行执行并发 HTTP 请求
- php - HTML/PHP 表单未向 phpadmin 数据库插入数据
- scala - 通过while循环对数组元素求和