如何从元素中删除所有属性 [英] How to remove all attributes from element

查看:79
本文介绍了如何从元素中删除所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to remove all attributes of the specific elements througout the document. I'm trying something like this:

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

Here I'm trying to delete all attributes from all tables in the document using xpath, but it doesn't work.

推荐答案

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

This is one possible way, assuming that you want to remove all attributes of certain element, say table :

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

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

The code above loop through all table that contains any attribute, then call clear() method of the elemet's attrib property, since the property is simply a python dictionary.

这篇关于如何从元素中删除所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆