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