我正在使用Google App Engine和Python2.7和lxml 2.3.5,我的服务器收到了我想要清理的html,但我想保留样式属性。
cleaner=lxml.html.clean.Cleaner()
cleaner.clean_html(html_str)但是样式属性被从html字符串中剥离。我见过lxml 3.2的解决方案,但似乎没有一个适合我(如何保留内联CSS样式...)。有什么想法吗?
发布于 2015-01-07 11:44:26
我们使用这个技巧来清理我们的HTML,因为目前还不能在GAE上使用最新的lxml版本(但要小心使用猴子补丁!):
import lxml.html.clean
def cleanup(s):
if s == '':
return ''
safe_attrs = list(lxml.html.clean.defs.safe_attrs) + ['style', 'bgcolor']
lxml.html.clean.defs.safe_attrs = safe_attrs
lxml.html.clean.Cleaner.safe_attrs = lxml.html.clean.defs.safe_attrs
cleaner = lxml.html.clean.Cleaner(
style=False, remove_tags=['body'], safe_attrs_only=True,
safe_attrs=safe_attrs, kill_tags=['title'])
return cleaner.clean_html(s)https://stackoverflow.com/questions/27807792
复制相似问题