1 """Utilities for working with HTML."""
3 from html5lib import sanitizer, serializer, tokenizer, treebuilders, treewalkers
5 class HTMLSanitizerMixin(sanitizer.HTMLSanitizerMixin):
6 acceptable_elements = ('a', 'abbr', 'acronym', 'address', 'b', 'big',
7 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col',
8 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'font',
9 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd',
10 'li', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike',
11 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead',
12 'tr', 'tt', 'u', 'ul', 'var')
14 acceptable_attributes = ('abbr', 'align', 'alt', 'axis', 'border',
15 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'cite',
16 'cols', 'colspan', 'datetime', 'dir', 'frame', 'headers', 'height',
17 'href', 'hreflang', 'hspace', 'lang', 'longdesc', 'name', 'nohref',
18 'noshade', 'nowrap', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope',
19 'span', 'src', 'start', 'summary', 'title', 'type', 'valign', 'vspace',
22 allowed_elements = acceptable_elements
23 allowed_attributes = acceptable_attributes
24 allowed_css_properties = ()
25 allowed_css_keywords = ()
26 allowed_svg_properties = ()
28 class HTMLSanitizer(tokenizer.HTMLTokenizer, HTMLSanitizerMixin):
31 for token in tokenizer.HTMLTokenizer.__iter__(self):
32 token = self.sanitize_token(token)
36 def sanitize_html(html):
37 """Sanitizes an HTML fragment."""
38 p = html5lib.HTMLParser(tokenizer=HTMLSanitizer,
39 tree=treebuilders.getTreeBuilder("dom"))
40 dom_tree = p.parseFragment(html)
41 walker = treewalkers.getTreeWalker("dom")
42 stream = walker(dom_tree)
43 s = serializer.HTMLSerializer(omit_optional_tags=False,
44 quote_attr_values=True)
45 output_generator = s.serialize(stream)
46 return u''.join(output_generator)