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

Hel*_*dan 5 python lxml

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

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
Run Code Online (Sandbox Code Playgroud)

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

har*_*r07 5

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

for table in root.xpath('//table[@*]'):
    table.attrib.clear()
Run Code Online (Sandbox Code Playgroud)

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