问题
如何使用 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/