如何从元素中删除所有属性

How to remove all attributes from element

如何删除整个文档中特定元素的所有属性。我正在尝试这样的事情:

from bs4 import UnicodeDammit
from lxml import html

content = open("source.html").read()
document = UnicodeDammit(content, is_html=True)
parser = html.HTMLParser(encoding=document.original_encoding)
root = html.document_fromstring(content, parser=parser)

for attr in root.xpath('.//table/@*'):
    del attr.attrib

我在这里尝试使用 xpath 删除文档中所有表的所有属性,但它不起作用。

这是一种可能的方法,假设您要删除某个元素的 所有 属性,比如 table :

for table in root.xpath('//table[@*]'):
    table.attrib.clear()

上面的代码遍历所有包含任何属性的 table,然后调用元素 attrib 属性 的 clear() 方法,因为 属性只是一个 python 字典。