【问题标题】:Remove a bad tag completely with html5lib.sanitizer使用 html5lib.sanitizer 完全删除坏标签
【发布时间】:2011-08-27 07:25:39
【问题描述】:

我正在尝试按照docs 中的建议使用 html5lib.sanitizer 来清理用户输入

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

补丁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 在非常奇怪的地方(例如 src attrs 周围)插入了&lt;p&gt;&lt;/p&gt; 标签。到目前为止,html5lib 似乎是最好的东西,如果我可以让它删除标签而不是转义它们。

【问题讨论】:

  • 这取决于您要如何选择要剥离的标签。您是否要 (a) 仅去除您指定的几个标签,即列入黑名单,或 (b) 去除除您指定的标签以外的所有标签,即列入白名单或 (c) 其他标签?

标签: python tokenize html-sanitizing html5lib sanitizer


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 2014-09-25
    • 2019-12-20
    • 2020-07-23
    相关资源
    最近更新 更多