def sanitize_html5lib(input):
from html5lib import treebuilders, treewalkers, serializer, sanitizer<EOL>p = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer, tree=treebuilders.getTreeBuilder("<STR_LIT>"))<EOL>dom_tree = p.parseFragment(input)<EOL>walker = treewalkers.getTreeWalker("<STR_LIT>")<EOL>stream = walker(dom_tree)<EOL>s = serializer.htmlserializer.HTMLSerializer(omit_optional_tags=False)<EOL>return "<STR_LIT>".join(s.serialize(stream))<EOL>
Removes any unwanted HTML tags and attributes, using html5lib.

>>> sanitize_html5lib("foobar<p>adf<i></p>abc</i>")
u'foobar<p>adf<i></i></p><i>abc</i>'
>>> sanitize_html5lib('foobar<p style="color:red; remove:me; background-image: url(http://example.com/test.php?query_string=bad);">adf<script>alert("Uhoh!")</script><i></p>abc</i>')
u'foobar<p style="color: red;">adf&lt;script&gt;alert("Uhoh!")&lt;/script&gt;<i></i></p><i>abc</i>'