Libxml Cleaner将不需要的<p>标签添加到HTML片段中

Wyl*_*lie 5 python parsing libxml2

我正在尝试使用libxml的HTML清理程序清理用户输入以防止XSS注入.当我输入这样的字符串时:

Normal text <b>Bold text</b>
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

<p>Normal text <b>Bold text</b></p>
Run Code Online (Sandbox Code Playgroud)

我想摆脱<p>围绕我所有输入的标签.


这是目前正在进行清洁的功能:

from lxml.html import clean

cleaner = clean.Cleaner(
    scripts = True,
    javascript = True,
    allow_tags = None,
)

def sanitize_html(html):
    return cleaner.clean_html(html)
Run Code Online (Sandbox Code Playgroud)

在一个不相关的说明中,上面的代码有一行:allow_tags = None我试图删除所有HTML标记.libxml是否具有白名单功能,我允许某些标签?

Sea*_*ean 3

所有TEXT片段/节点都必须包含在某种元素中。libxml将尝试尽力解决此问题。

def sanitize_html(html):
    cleaned_html = cleaner.clean_html(html)
    return re.sub(r'</p>$', '', re.sub(r'^<p>', '', cleaned_html))
Run Code Online (Sandbox Code Playgroud)

缓存已编译的正则表达式或找到更有效的方法来完成此操作留给查看者作为练习。无需重新审查 libxml2,我认为您可以摆脱困境:

return cleaned_html[3:-4]     # Single slice operation
return cleaned_html[3:][:-4]
Run Code Online (Sandbox Code Playgroud)