gpt4 book ai didi

python - Libxml Cleaner 将不需要的

标记添加到 HTML 片段

转载 作者:太空狗 更新时间:2023-10-30 01:24:05 24 4
gpt4 key购买 nike

我正在尝试使用 libxml 的 HTML 清理器清理用户输入以防止 XSS 注入(inject)。当我输入这样的字符串时:

Normal text <b>Bold text</b>

我得到这个:

<p>Normal text <b>Bold text</b></p>

我想去掉 <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)

顺便说一句,上面的代码只有一行:allow_tags = None我试图删除所有 HTML 标签的地方。 libxml 是否具有我允许某些标签的白名单功能?

最佳答案

所有TEXT 片段/节点必须包含在某种元素中。 libxml 将尝试尽可能地解决这个问题。

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

缓存已编译的正则表达式或寻找更有效的方法来执行此操作留给查看者作为练习。在不重新审查 libxml2 的情况下,我认为您可以摆脱困境:

return cleaned_html[3:-4]     # Single slice operation
return cleaned_html[3:][:-4]

关于python - Libxml Cleaner 将不需要的 <p> 标记添加到 HTML 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6448802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com