从HTML标记中删除某些属性 [英] remove certain attributes from HTML tags
问题描述
如何从HTML代码中删除某些属性,例如id,样式,类等?
How can I remove certain attributes such as id, style, class, etc. from HTML code?
我认为我可以使用 lxml.html.clean模块,但是事实证明,我只能使用Clean(style=True).clean_html(code)
删除样式属性.我不希望在此任务中使用正则表达式(属性可能会发生变化).
I thought I could use the lxml.html.clean module, but as it turned out I can only remove style attributes with Clean(style=True).clean_html(code)
. I'd prefer not to use regular expressions for this task (attributes could change).
我想拥有的东西:
from lxml.html.clean import Cleaner
code = '<tr id="ctl00_Content_AdManagementPreview_DetailView_divNova" class="Extended" style="display: none;">'
cleaner = Cleaner(style=True, id=True, class=True)
cleaned = cleaner.clean_html(code)
print cleaned
'<tr>'
提前谢谢!
推荐答案
cleaner.Cleaner.__call__
具有safe_attrs_only
参数.设置为True
时,仅保留clean.defs.safe_attrs
中的属性.您可以通过更改clean.defs.safe_attrs
删除任何或所有属性.只要确保完成后再将其更改即可.
cleaner.Cleaner.__call__
has a safe_attrs_only
parameter. When set to True
, only attributes in clean.defs.safe_attrs
are preserved. You can remove any or all attributes by changing clean.defs.safe_attrs
. Just be sure to change it back when you are done.
import lxml.html.clean as clean
code = '<tr id="ctl00_Content_AdManagementPreview_DetailView_divNova" class="Extended" style="display: none;">'
safe_attrs = clean.defs.safe_attrs
cleaner = clean.Cleaner(safe_attrs_only=True, safe_attrs=frozenset())
cleansed = cleaner.clean_html(code)
print(cleansed)
收益
<tr></tr>
这篇关于从HTML标记中删除某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!