【问题标题】:How to remove all attributes from element如何从元素中删除所有属性
【发布时间】:2015-12-15 09:25:02
【问题描述】:

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

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 从文档中的所有表中删除所有属性,但它不起作用。

【问题讨论】:

  • 是的,但考虑到 xpath 应该是这样的:...
    应该变成 ...

标签: python lxml


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2019-08-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多