Path: blob/master/venv/Lib/site-packages/lxml/html/soupparser.py
811 views
"""External interface to the BeautifulSoup HTML parser.1"""23__all__ = ["fromstring", "parse", "convert_tree"]45import re6from lxml import etree, html78try:9from bs4 import (10BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,11Declaration, Doctype)12_DECLARATION_OR_DOCTYPE = (Declaration, Doctype)13except ImportError:14from BeautifulSoup import (15BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,16Declaration)17_DECLARATION_OR_DOCTYPE = Declaration181920def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):21"""Parse a string of HTML data into an Element tree using the22BeautifulSoup parser.2324Returns the root ``<html>`` Element of the tree.2526You can pass a different BeautifulSoup parser through the27`beautifulsoup` keyword, and a diffent Element factory function28through the `makeelement` keyword. By default, the standard29``BeautifulSoup`` class and the default factory of `lxml.html` are30used.31"""32return _parse(data, beautifulsoup, makeelement, **bsargs)333435def parse(file, beautifulsoup=None, makeelement=None, **bsargs):36"""Parse a file into an ElemenTree using the BeautifulSoup parser.3738You can pass a different BeautifulSoup parser through the39`beautifulsoup` keyword, and a diffent Element factory function40through the `makeelement` keyword. By default, the standard41``BeautifulSoup`` class and the default factory of `lxml.html` are42used.43"""44if not hasattr(file, 'read'):45file = open(file)46root = _parse(file, beautifulsoup, makeelement, **bsargs)47return etree.ElementTree(root)484950def convert_tree(beautiful_soup_tree, makeelement=None):51"""Convert a BeautifulSoup tree to a list of Element trees.5253Returns a list instead of a single root Element to support54HTML-like soup with more than one root element.5556You can pass a different Element factory through the `makeelement`57keyword.58"""59root = _convert_tree(beautiful_soup_tree, makeelement)60children = root.getchildren()61for child in children:62root.remove(child)63return children646566# helpers6768def _parse(source, beautifulsoup, makeelement, **bsargs):69if beautifulsoup is None:70beautifulsoup = BeautifulSoup71if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs372if 'convertEntities' not in bsargs:73bsargs['convertEntities'] = 'html'74if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs475if 'features' not in bsargs:76bsargs['features'] = 'html.parser' # use Python html parser77tree = beautifulsoup(source, **bsargs)78root = _convert_tree(tree, makeelement)79# from ET: wrap the document in a html root element, if necessary80if len(root) == 1 and root[0].tag == "html":81return root[0]82root.tag = "html"83return root848586_parse_doctype_declaration = re.compile(87r'(?:\s|[<!])*DOCTYPE\s*HTML'88r'(?:\s+PUBLIC)?(?:\s+(\'[^\']*\'|"[^"]*"))?'89r'(?:\s+(\'[^\']*\'|"[^"]*"))?',90re.IGNORECASE).match919293class _PseudoTag:94# Minimal imitation of BeautifulSoup.Tag95def __init__(self, contents):96self.name = 'html'97self.attrs = []98self.contents = contents99100def __iter__(self):101return self.contents.__iter__()102103104def _convert_tree(beautiful_soup_tree, makeelement):105if makeelement is None:106makeelement = html.html_parser.makeelement107108# Split the tree into three parts:109# i) everything before the root element: document type110# declaration, comments, processing instructions, whitespace111# ii) the root(s),112# iii) everything after the root: comments, processing113# instructions, whitespace114first_element_idx = last_element_idx = None115html_root = declaration = None116for i, e in enumerate(beautiful_soup_tree):117if isinstance(e, Tag):118if first_element_idx is None:119first_element_idx = i120last_element_idx = i121if html_root is None and e.name and e.name.lower() == 'html':122html_root = e123elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):124declaration = e125126# For a nice, well-formatted document, the variable roots below is127# a list consisting of a single <html> element. However, the document128# may be a soup like '<meta><head><title>Hello</head><body>Hi129# all<\p>'. In this example roots is a list containing meta, head130# and body elements.131if first_element_idx is None:132pre_root = post_root = []133roots = beautiful_soup_tree.contents134else:135pre_root = beautiful_soup_tree.contents[:first_element_idx]136roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]137post_root = beautiful_soup_tree.contents[last_element_idx+1:]138139# Reorganize so that there is one <html> root...140if html_root is not None:141# ... use existing one if possible, ...142i = roots.index(html_root)143html_root.contents = roots[:i] + html_root.contents + roots[i+1:]144else:145# ... otherwise create a new one.146html_root = _PseudoTag(roots)147148convert_node = _init_node_converters(makeelement)149150# Process pre_root151res_root = convert_node(html_root)152prev = res_root153for e in reversed(pre_root):154converted = convert_node(e)155if converted is not None:156prev.addprevious(converted)157prev = converted158159# ditto for post_root160prev = res_root161for e in post_root:162converted = convert_node(e)163if converted is not None:164prev.addnext(converted)165prev = converted166167if declaration is not None:168try:169# bs4 provides full Doctype string170doctype_string = declaration.output_ready()171except AttributeError:172doctype_string = declaration.string173174match = _parse_doctype_declaration(doctype_string)175if not match:176# Something is wrong if we end up in here. Since soupparser should177# tolerate errors, do not raise Exception, just let it pass.178pass179else:180external_id, sys_uri = match.groups()181docinfo = res_root.getroottree().docinfo182# strip quotes and update DOCTYPE values (any of None, '', '...')183docinfo.public_id = external_id and external_id[1:-1]184docinfo.system_url = sys_uri and sys_uri[1:-1]185186return res_root187188189def _init_node_converters(makeelement):190converters = {}191ordered_node_types = []192193def converter(*types):194def add(handler):195for t in types:196converters[t] = handler197ordered_node_types.append(t)198return handler199return add200201def find_best_converter(node):202for t in ordered_node_types:203if isinstance(node, t):204return converters[t]205return None206207def convert_node(bs_node, parent=None):208# duplicated in convert_tag() below209try:210handler = converters[type(bs_node)]211except KeyError:212handler = converters[type(bs_node)] = find_best_converter(bs_node)213if handler is None:214return None215return handler(bs_node, parent)216217def map_attrs(bs_attrs):218if isinstance(bs_attrs, dict): # bs4219attribs = {}220for k, v in bs_attrs.items():221if isinstance(v, list):222v = " ".join(v)223attribs[k] = unescape(v)224else:225attribs = dict((k, unescape(v)) for k, v in bs_attrs)226return attribs227228def append_text(parent, text):229if len(parent) == 0:230parent.text = (parent.text or '') + text231else:232parent[-1].tail = (parent[-1].tail or '') + text233234# converters are tried in order of their definition235236@converter(Tag, _PseudoTag)237def convert_tag(bs_node, parent):238attrs = bs_node.attrs239if parent is not None:240attribs = map_attrs(attrs) if attrs else None241res = etree.SubElement(parent, bs_node.name, attrib=attribs)242else:243attribs = map_attrs(attrs) if attrs else {}244res = makeelement(bs_node.name, attrib=attribs)245246for child in bs_node:247# avoid double recursion by inlining convert_node(), see above248try:249handler = converters[type(child)]250except KeyError:251pass252else:253if handler is not None:254handler(child, res)255continue256convert_node(child, res)257return res258259@converter(Comment)260def convert_comment(bs_node, parent):261res = html.HtmlComment(bs_node)262if parent is not None:263parent.append(res)264return res265266@converter(ProcessingInstruction)267def convert_pi(bs_node, parent):268if bs_node.endswith('?'):269# The PI is of XML style (<?as df?>) but BeautifulSoup270# interpreted it as being SGML style (<?as df>). Fix.271bs_node = bs_node[:-1]272res = etree.ProcessingInstruction(*bs_node.split(' ', 1))273if parent is not None:274parent.append(res)275return res276277@converter(NavigableString)278def convert_text(bs_node, parent):279if parent is not None:280append_text(parent, unescape(bs_node))281return None282283return convert_node284285286# copied from ET's ElementSoup287288try:289from html.entities import name2codepoint # Python 3290except ImportError:291from htmlentitydefs import name2codepoint292293294handle_entities = re.compile(r"&(\w+);").sub295296297try:298unichr299except NameError:300# Python 3301unichr = chr302303304def unescape(string):305if not string:306return ''307# work around oddities in BeautifulSoup's entity handling308def unescape_entity(m):309try:310return unichr(name2codepoint[m.group(1)])311except KeyError:312return m.group(0) # use as is313return handle_entities(unescape_entity, string)314315316