python - 使用 Python 和 lxml 从 HTML 中删除类属性

标签 python html lxml

问题

如何使用 python 和 lxml 从 html 中删除类属性?

例子

我有:

<p class="DumbClass">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>

我要:

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>

到目前为止我尝试了什么

我已经 checkout lxml.html.clean.Cleaner但是,它没有去除类属性的方法。您可以设置 safe_attrs_only=True 但是,这不会删除类属性。

大量搜索没有找到任何可行的方法。我认为 class 用于 html 和 python 的事实进一步混淆了搜索结果。许多结果似乎也严格处理 xml。

我对其他提供人性化界面的 python 模块持开放态度。

非常感谢。


解决方案

感谢@Dan Roberts 在下面的回答,我想出了以下解决方案。呈现给 future 来到这里试图解决相同问题的人们。

import lxml.html

# Our html string we want to remove the class attribute from
html_string = '<p class="DumbClass">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>'

# Parse the html
html = lxml.html.fromstring(html_string)

# Print out our "Before"
print lxml.html.tostring(html)

# .xpath below gives us a list of all elements that have a class attribute
# xpath syntax explained:
# // = select all tags that match our expression regardless of location in doc
# * = match any tag
# [@class] = match all class attributes
for tag in html.xpath('//*[@class]'):
    # For each element with a class attribute, remove that class attribute
    tag.attrib.pop('class')

# Print out our "After"
print lxml.html.tostring(html)

最佳答案

目前我无法对此进行测试,但这似乎是一般的想法

for tag in node.xpath('//*[@class]'):
    tag.attrib.pop('class')

关于python - 使用 Python 和 lxml 从 HTML 中删除类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10037289/

相关文章:

python - 在 pandas 中,有没有办法将行旋转到其他行的末尾?

jquery - 如何重叠多个div?

python - 在 subprocess.Popen 命令中使用变量

python - 使用一体式 pygtk 安装程序 Windows 7 不起作用?

python - 如何将 Datetime 和 int 功能与 Scikit learn 混合使用?

javascript - 在 Internet 区域处于高安全模式时,网站在 IE8 中出现乱码

javascript - jQuery UI 弹跳效果对齐 Firefox 和 IE8 中剩余的元素

python - 从 scrapy.selector 导入选择器错误

python - xpath获取style标签内容的方法

python - 删除节点lxml python