如何在Python中使用lxml.html.clean.Cleaner()保留内联CSS样式?

lav*_*iex 11 python lxml lxml.html

我正在尝试使用lxml.html.clean.Cleaner()清理html表.我需要去掉javascript属性,但是想保留内联css样式.我认为style = False是默认设置:

import lxml.html.clean
cleaner = lxml.html.clean.Cleaner()
Run Code Online (Sandbox Code Playgroud)

但是,当我打电话的时候 cleaner.clean_html(doc)

<span style="color:#008800;">67.51</span>
Run Code Online (Sandbox Code Playgroud)

会变成

<span>67.51</span>
Run Code Online (Sandbox Code Playgroud)

基本上,风格不会保留.我试着添加:

cleaner.style= False
Run Code Online (Sandbox Code Playgroud)

它无济于事.

更新:我在Dreamhost上使用Python 2.6.6 + lxml 3.2.4,在本地Macbook上使用Python 2.7.5 + lxml 3.2.4.结果相同.另一件事:我的html中有一个与javacript相关的属性:

<td style="cursor:pointer;">Ticker</td>

是不是lxml剥离了这个javacript相关的风格,并对待其他风格相同?希望不是.

感谢您的任何见解!

mzj*_*zjn 10

如果你设置它是有效的cleaner.safe_attrs_only = False.

"安全"属性集(Cleaner.safe_attrs)在lxml.html.defs模块(源代码)中定义,style不包含在集合中.

但比cleaner.safe_attrs_only = False使用更好Cleaner(safe_attrs=lxml.html.defs.safe_attrs | set(['style'])).这将保留style并同时保护其他不安全的属性.

演示代码:

from lxml import html
from lxml.html import clean

s ='<marquee><span style="color: #008800;">67.51</span></marquee>'
doc = html.fromstring(s)
cleaner = clean.Cleaner(safe_attrs=html.defs.safe_attrs | set(['style']))

print html.tostring(cleaner.clean_html(doc))
Run Code Online (Sandbox Code Playgroud)

输出:

<div><span style="color: #008800;">67.51</span></div>
Run Code Online (Sandbox Code Playgroud)