Python 如何从元素中删除所有属性
如何删除文档中特定元素的所有属性。我正在尝试这样的事情:Python 如何从元素中删除所有属性,python,lxml,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_
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从文档中的所有表中删除所有属性,但它不起作用。这是一种可能的方法,假设您要删除某些元素的所有属性,例如
表:
for table in root.xpath('//table[@*]'):
table.attrib.clear()
上面的代码循环遍历包含任何属性的所有表
,然后调用elemet的attrib
属性的clear()
方法,因为该属性只是一个python字典。是的,但考虑到xpath应该是这样的:。。。应该成为。。。