Python lxml 清理元素属性:保留子元素内容
Python lxml 清理元素属性:保留子元素内容
你可以使用 Python 的 lxml 库中的 strip_attributes 方法来清理元素属性。该方法可以删除指定的元素属性,但会保留子元素。
以下是一个示例代码,它将删除 <div> 元素中的 class 和 style 属性,但会保留其子元素:
from lxml import etree
html_str = """
<div class='container' style='padding: 10px;'>
<h1>Title</h1>
<p>Content</p>
</div>
"""
html = etree.HTML(html_str)
div = html.xpath('//div')[0]
etree.strip_attributes(div, 'class', 'style')
print(etree.tostring(div).decode())
输出结果为:
<div>
<h1>Title</h1>
<p>Content</p>
</div>
可以看到,class 和 style 属性已被删除,但子元素保留了下来。
原文地址: https://www.cveoy.top/t/topic/ospI 著作权归作者所有。请勿转载和采集!