Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.
Bleach can also linkify text safely, applying filters that Django's urlize filter cannot, and optionally setting rel attributes, even on links already in the text.
Bleach is intended for sanitizing text from untrusted sources. If you find yourself jumping through hoops to allow your site administrators to do lots of things, you're probably outside the use cases. Either trust those users, or don't.
Because it relies on html5lib, Bleach is as good as modern browsers at dealing with weird, quirky HTML fragments. And any of Bleach's methods will fix unbalanced or mis-nested tags.
import bleach # Some potentially dangerous user-generated HTML html_input = '<p>Hello, <script>alert("XSS!");</script>world!</p>' # Use bleach to clean the HTML clean_html = bleach.clean(html_input, tags=['p'], strip=True) print(clean_html) # Output: '<p>Hello, world!</p>' # or clean CSS: css_input = 'color: expression(alert("XSS!"));' # Use bleach to clean the CSS clean_css = bleach.clean(css_input, styles=['color'], strip=True) print(clean_css) # Output: 'color: #000000;'