def parse_html5(raw, decoder=None, log=None, discard_namespaces=False, line_numbers=True, linenumber_attribute=None, replace_entities=True, fix_newlines=True): if isinstance(raw, bytes): raw = xml_to_unicode(raw)[0] if decoder is None else decoder(raw) raw = fix_self_closing_cdata_tags(raw) # TODO: Handle this in the parser if replace_entities: raw = xml_replace_entities(raw) if fix_newlines: raw = raw.replace('\r\n', '\n').replace('\r', '\n') raw = replace_chars.sub('', raw) stream_class = partial(FastStream, track_position=line_numbers) stream = stream_class(raw) builder = partial(NoNamespaceTreeBuilder if discard_namespaces else TreeBuilder, linenumber_attribute=linenumber_attribute) while True: try: parser = HTMLParser(tree=builder, track_positions=line_numbers, namespaceHTMLElements=not discard_namespaces) with warnings.catch_warnings(): warnings.simplefilter('ignore', category=DataLossWarning) try: parser.parse(stream, parseMeta=False, useChardet=False) finally: parser.tree.proxy_cache = None except NamespacedHTMLPresent as err: raw = re.sub(r'<\s*/{0,1}(%s:)' % err.prefix, lambda m: m.group().replace(m.group(1), ''), raw, flags=re.I) stream = stream_class(raw) continue break root = parser.tree.getDocument() if (discard_namespaces and root.tag != 'html') or ( not discard_namespaces and (root.tag != '{%s}%s' % (namespaces['html'], 'html') or root.prefix)): raise ValueError('Failed to parse correctly, root has tag: %s and prefix: %s' % (root.tag, root.prefix)) return root
def validate_url(self, url, use_w3c=True, quite=True): 'validate urls with the w3c validator. Need an Internet Connection' client = Client() response = client.get(url, follow=True) if response.status_code == 200: src = response.content treebuilder = treebuilders.getTreeBuilder("etree") parser = HTMLParser(tree=treebuilder, strict=True) try: parser.parse(src) except Exception as ex: pass if not parser.errors and use_w3c: #uploading to w3c w3c = w3c_client(src) if w3c and not w3c[0]: print('%s: %s' % ( url, w3c[1], )) if not quite: for i in w3c[2]['messages']: print(i['messageid']) print('\t%s' % (i['message'], )) #self.assertTrue(w3c[0]) else: print('skipping html check %s', (response.status_code, ))
def runValidatorTest(self, test): p = HTMLParser(tokenizer=HTMLConformanceChecker) p.parse(test['input']) errorCodes = [errorcode for position, errorcode, datavars in p.errors] if test.has_key('fail-if'): self.failIf(test['fail-if'] in errorCodes) if test.has_key('fail-unless'): self.failUnless(test['fail-unless'] in errorCodes)
def cutHtml(text, max_len): parser = HTMLParser(tree=treebuilders.getTreeBuilder("lxml")) etree_document = parser.parse(text) sentinel = Sentinel(max_len) processItem(etree_document.getroot(), sentinel) if sentinel.stop: walker = treewalkers.getTreeWalker("lxml") stream = walker(etree_document.getroot().getchildren()[1]) s = serializer.htmlserializer.HTMLSerializer(omit_optional_tags=False) output_generator = s.serialize(stream) output = [] for item in output_generator: output.append(item) output = output[1:-1] # remove <body></body> return ''.join(output) return None
def validate_html(self, response): # only import this stuff if we need it! from html5lib.html5parser import HTMLParser from html5lib.filters.validator import HTMLConformanceChecker import pprint p = HTMLParser() p.parse(response.body) if (p.errors and not (len(p.errors) == 1 and p.errors[0][1] == 'unknown-doctype')): lines = response.body.splitlines() for (line, col), error, vars in p.errors: print "----------------------------------" print "Error: %s on line %s, column %s" % (error, line, col) print "%5d: %s" % (line, lines[line-1]) print " %s^" % (" " * col,) self.assert_(False)
def validate_html(self, response): # only import this stuff if we need it! from html5lib.html5parser import HTMLParser from html5lib.filters.validator import HTMLConformanceChecker import pprint p = HTMLParser() p.parse(response.body) if (p.errors and not (len(p.errors) == 1 and p.errors[0][1] == 'unknown-doctype')): lines = response.body.splitlines() for (line, col), error, vars in p.errors: print "----------------------------------" print "Error: %s on line %s, column %s" % (error, line, col) print "%5d: %s" % (line, lines[line - 1]) print " %s^" % (" " * col, ) self.assert_(False)
def __init__(self,value,element): self.element=element self.valid = True self.parser = HTMLParser(strict=True) if value.lower().find('<?import ') >= 0: self.log(SecurityRisk({"parent":self.element.parent.name, "element":self.element.name, "tag":"?import"})) try: etree = self.parser.parseFragment(value) if self.valid: self.log(ValidHtml({"parent":self.element.parent.name, "element":self.element.name})) from pprint import pprint for tag in etree.iter(): if tag.tag != "DOCUMENT_FRAGMENT": self.handle_tag(tag.tag.split('}')[-1], tag.attrib, tag.text) except ParseError as msg: element = self.element offset = [element.line - element.dispatcher.locator.getLineNumber(), - element.dispatcher.locator.getColumnNumber()] match = re.search(', at line (\d+), column (\d+)',str(msg)) if match: offset[0] += int(match.group(1))-1 element.log(NotHtml({"parent":element.parent.name, "element":element.name, "message":"Invalid HTML", "value": str(msg)}),offset)
def openLogin(): logging.info('Loading login page...') s = requests.Session() # trigger login page resp = s.get('https://developer.apple.com/download/', headers={ 'User-Agent': UA }) resp.raise_for_status() parser = HTMLParser(getTreeBuilder('dom')) parser = parser.parse(resp.text) form_input = bakeRequest(parser) logging.info('Logging in ...') resp = s.post('https://idmsa.apple.com/IDMSWebAuth/authenticate', headers={'User-Agent': UA}, data=form_input) resp.raise_for_status() if resp.url.find('authenticate') > 0: raise Exception('Login failed') logging.info('Fetching download token...') resp = s.post('https://developer.apple.com/services-account/QH65B2/downloadws/listDownloads.action', headers={'User-Agent': UA}, data='') resp.raise_for_status() generateDownload(s.cookies.items())
def thumbnails(html): """ Given a HTML string, converts paths in img tags to thumbnail paths, using Mezzanine's ``thumbnail`` template tag. Used as one of the default values in the ``RICHTEXT_FILTERS`` setting. """ from django.conf import settings from html5lib.treebuilders import getTreeBuilder from html5lib.html5parser import HTMLParser #from mezzanine.core.templatetags.mezzanine_tags import thumbnail from asylum_custom.templatetags.asylum_tags import thumbnail dom = HTMLParser(tree=getTreeBuilder("dom")).parse(html) for img in dom.getElementsByTagName("img"): src = img.getAttribute("src") width = img.getAttribute("width") height = img.getAttribute("height") if src and width and height: src = settings.MEDIA_URL + thumbnail(src, width, height) img.setAttribute("src", src) nodes = dom.getElementsByTagName("body")[0].childNodes return "".join([node.toxml() for node in nodes])
def openLogin(): logging.info('Loading login page...') s = requests.Session() # trigger login page resp = s.get('https://developer.apple.com/download/', headers={'User-Agent': UA}) resp.raise_for_status() parser = HTMLParser(getTreeBuilder('dom')) parser = parser.parse(resp.text) form_input = bakeRequest(parser) logging.info('Logging in ...') resp = s.post('https://idmsa.apple.com/IDMSWebAuth/authenticate', headers={'User-Agent': UA}, data=form_input) resp.raise_for_status() if resp.url.find('authenticate') > 0: raise Exception('Login failed') logging.info('Fetching download token...') resp = s.post( 'https://developer.apple.com/services-account/QH65B2/downloadws/listDownloads.action', headers={'User-Agent': UA}, data='') resp.raise_for_status() generateDownload(s.cookies.items())
def normalize_html(stream): p = HTMLParser(tokenizer=HTMLSanitizer) return ''.join([token.toxml() for token in p.parseFragment(stream).childNodes])
def fixHtml(html): p = HTMLParser() return ''.join( [token.toxml() for token in p.parseFragment(html).childNodes])
class HTMLValidator: htmltags = [ "a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "big", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "data", "datagrid", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "em", "eventsource", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "isindex", "kbd", "label", "legend", "li", "link", "m", "main", "mark", "map", "menu", "meta", "meter", "nav", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "slot", "small", "source", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "xmp", "plaintext", "embed", "comment", "listing", "video", "wbr"] acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'big', 'blockquote', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'data', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'eventsource', 'fieldset', "figcaption", 'figure', 'footer', 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'hr', 'i', 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'main', 'map', 'mark', 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'time', 'tfoot', 'th', 'thead', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'noscript', 'wbr'] acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'allowfullscreen', 'allowpaymentrequest', 'alt', 'as', 'autoplay', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'axis', 'background', 'balance', 'bgcolor', 'bgproperties', 'border', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding', 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff', 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'compact', 'contenteditable', 'coords', 'crossorigin', 'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'decoding', 'default', 'delay', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'dynsrc', 'enctype','end', 'enterkeyhint', 'face', 'for', 'form', 'formenctype', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode', 'is', 'ismap', 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype', 'kind','keytype', 'label', 'lang', 'leftspacing', 'loading', 'list', 'longdesc', 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nohref', 'nonce', 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'playsinline', 'point-size', 'poster', 'preload', 'prompt', 'pqg', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'repeat-max', 'repeat-min', 'replace', 'required', 'rev', 'reversed', 'rightspacing', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'spellcheck', 'src', 'srclang', 'srcset', 'start', 'step', 'summary', 'suppress', 'tabindex', 'target', 'template', 'title', 'toppadding', 'translate', 'type', 'unselectable', 'usemap', 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap', 'xml:lang', 'xmlns'] acceptable_css_properties = ['azimuth', 'background', 'background-color', 'border', 'border-bottom', 'border-bottom-color', 'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-left', 'border-left-color', 'border-left-style', 'border-left-width', 'border-right', 'border-right-color', 'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top', 'border-top-color', 'border-top-style', 'border-top-width', 'border-width', 'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'list-style-type', 'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom', 'padding-left', 'padding-right', 'padding-top', 'pause', 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', 'white-space', 'width'] # survey of common keywords found in feeds acceptable_css_keywords = ['aqua', 'auto', 'black', 'block', 'blue', 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', 'transparent', 'underline', 'white', 'yellow'] valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' + '\d?\.?\d?\d(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$') mathml_elements = ['annotation', 'annotation-xml', 'maction', 'math', 'merror', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none', 'semantics'] mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth', 'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows', 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize', 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection', 'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink'] # svgtiny - foreignObject + linearGradient + radialGradient + stop - image svg_elements = ['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern', 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use'] # svgtiny + class + opacity + offset + xmlns + xmlns:xlink svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic', 'arabic-form', 'ascent', 'attributeName', 'attributeType', 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height', 'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity', 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max', 'min', 'name', 'offset', 'opacity', 'orient', 'origin', 'overline-position', 'overline-thickness', 'panose-1', 'path', 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2', 'underline-position', 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1', 'y2', 'zoomAndPan'] def log(self,msg): offset = [self.element.line - 1 - self.element.dispatcher.locator.getLineNumber(), -self.element.dispatcher.locator.getColumnNumber()] self.element.log(msg, offset) def __init__(self,value,element): self.element=element self.valid = True self.parser = HTMLParser(strict=True) if value.lower().find('<?import ') >= 0: self.log(SecurityRisk({"parent":self.element.parent.name, "element":self.element.name, "tag":"?import"})) try: etree = self.parser.parseFragment(value) if self.valid: self.log(ValidHtml({"parent":self.element.parent.name, "element":self.element.name})) from pprint import pprint for tag in etree.iter(): if tag.tag != "DOCUMENT_FRAGMENT": self.handle_tag(tag.tag.split('}')[-1], tag.attrib, tag.text) except ParseError as msg: element = self.element offset = [element.line - element.dispatcher.locator.getLineNumber(), - element.dispatcher.locator.getColumnNumber()] match = re.search(', at line (\d+), column (\d+)',str(msg)) if match: offset[0] += int(match.group(1))-1 element.log(NotHtml({"parent":element.parent.name, "element":element.name, "message":"Invalid HTML", "value": str(msg)}),offset) def handle_tag(self, tag, attributes, text): if tag.lower() not in self.htmltags: self.log(NotHtml({"parent":self.element.parent.name, "element":self.element.name,"value":tag, "message": "Non-html tag"})) self.valid = False elif tag.lower() not in HTMLValidator.acceptable_elements: self.log(SecurityRisk({"parent":self.element.parent.name, "element":self.element.name, "tag":tag})) else: for (name,value) in attributes.iteritems(): if name.lower() == 'style': for evil in checkStyle(value): self.log(DangerousStyleAttr({"parent":self.element.parent.name, "element":self.element.name, "attr":"style", "value":evil})) elif name.lower() not in self.acceptable_attributes: # data-* attributes are acceptable if name.lower()[:5] != "data-": self.log(SecurityRiskAttr({"parent":self.element.parent.name, "element":self.element.name, "attr":name}))