从Python字符串中删除不在允许列表中的HTML标签 [英] Remove HTML tags not on an allowed list from a Python string

查看:89
本文介绍了从Python字符串中删除不在允许列表中的HTML标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文本和HTML的字符串.我想删除或以其他方式禁用某些HTML标记(例如<script>),同时允许其他标记,以便我可以在网页上安全地呈现它.我有一个允许的标签列表,如何处理字符串以删除任何其他标签?

I have a string containing text and HTML. I want to remove or otherwise disable some HTML tags, such as <script>, while allowing others, so that I can render it on a web page safely. I have a list of allowed tags, how can I process the string to remove any other tags?

推荐答案

这是使用 BeautifulSoup :

from bs4 import BeautifulSoup

VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br']

def sanitize_html(value):

    soup = BeautifulSoup(value)

    for tag in soup.findAll(True):
        if tag.name not in VALID_TAGS:
            tag.hidden = True

    return soup.renderContents()

如果您也要删除无效标签的内容,请用tag.extract()代替tag.hidden.

If you want to remove the contents of the invalid tags as well, substitute tag.extract() for tag.hidden.

您还可以考虑使用 lxml 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆