使用html5lib.sanitizer完全删除错误的标记

时间:2011-05-17 14:35:42

标签: python tokenize html-sanitizing html5lib sanitizer

我正在尝试使用html5lib.sanitizer来清理用户输入,如docs

中所示

问题是我想完全删除坏标签,而不是逃避它们(无论如何这似乎是一个坏主意)。

修补程序here中建议的解决方法无法按预期工作(它保留了<tag>content</tag>的内部内容。)

具体来说,我想做这样的事情:

输入:

<script>bad_thing();</script>
<style>* { background: #000; }</style>
<h1>Hello world</h1>
Lorem ipsum

输出:

<h1>Hello world</h1>
Lorem ipsum

关于如何实现它的任何想法?我尝试过BeautifulSoup,但它看起来效果不好,并且lxml在非常奇怪的地方插入<p></p>标签(例如在src attrs附近)。到目前为止,html5lib似乎是最好的用途,如果我可以让它删除标签而不是转义它们。

1 个答案:

答案 0 :(得分:1)

挑战在于还要删除不需要的嵌套标签。它并不漂亮,但它是朝着正确方向迈出的一步:

from lxml.html import fromstring
from lxml import etree

html = '''
<script>bad_thing();</script>
<style>* { background: #000; }</style>
<h1>Hello world<script>bad_thing();</script></h1>
Lorem ipsum
<script>bad_thing();</script>
<b>Bold Text</b>
'''

l = []
doc = fromstring(html)
for el in doc.xpath(".//h1|.//b"):
    i = etree.Element(el.tag)
    i.text, i.tail = el.text, el.tail
    l.append(etree.tostring(i))

print ''.join(l)

哪个输出:

<h1>Hello world</h1>
Lorem ipsum
<b>Bold Text</b>