Remove HTML tags not on an allowed list from a Python string

html, python

Solution

Here's a simple solution using 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()

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

You might also look into using lxml and Tidy.

Problem

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?

Original source

Related problems