Blame src/lxml/html/soupparser.py

rpm-build d9acb6
"""External interface to the BeautifulSoup HTML parser.
rpm-build d9acb6
"""
rpm-build d9acb6
rpm-build d9acb6
__all__ = ["fromstring", "parse", "convert_tree"]
rpm-build d9acb6
rpm-build d9acb6
import re
rpm-build d9acb6
from lxml import etree, html
rpm-build d9acb6
rpm-build d9acb6
try:
rpm-build d9acb6
    from bs4 import (
rpm-build d9acb6
        BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
rpm-build d9acb6
        Declaration, Doctype)
rpm-build d9acb6
    _DECLARATION_OR_DOCTYPE = (Declaration, Doctype)
rpm-build d9acb6
except ImportError:
rpm-build d9acb6
    from BeautifulSoup import (
rpm-build d9acb6
        BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
rpm-build d9acb6
        Declaration)
rpm-build d9acb6
    _DECLARATION_OR_DOCTYPE = Declaration
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
rpm-build d9acb6
    """Parse a string of HTML data into an Element tree using the
rpm-build d9acb6
    BeautifulSoup parser.
rpm-build d9acb6
rpm-build d9acb6
    Returns the root ``<html>`` Element of the tree.
rpm-build d9acb6
rpm-build d9acb6
    You can pass a different BeautifulSoup parser through the
rpm-build d9acb6
    `beautifulsoup` keyword, and a diffent Element factory function
rpm-build d9acb6
    through the `makeelement` keyword.  By default, the standard
rpm-build d9acb6
    ``BeautifulSoup`` class and the default factory of `lxml.html` are
rpm-build d9acb6
    used.
rpm-build d9acb6
    """
rpm-build d9acb6
    return _parse(data, beautifulsoup, makeelement, **bsargs)
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
rpm-build d9acb6
    """Parse a file into an ElemenTree using the BeautifulSoup parser.
rpm-build d9acb6
rpm-build d9acb6
    You can pass a different BeautifulSoup parser through the
rpm-build d9acb6
    `beautifulsoup` keyword, and a diffent Element factory function
rpm-build d9acb6
    through the `makeelement` keyword.  By default, the standard
rpm-build d9acb6
    ``BeautifulSoup`` class and the default factory of `lxml.html` are
rpm-build d9acb6
    used.
rpm-build d9acb6
    """
rpm-build d9acb6
    if not hasattr(file, 'read'):
rpm-build d9acb6
        file = open(file)
rpm-build d9acb6
    root = _parse(file, beautifulsoup, makeelement, **bsargs)
rpm-build d9acb6
    return etree.ElementTree(root)
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
def convert_tree(beautiful_soup_tree, makeelement=None):
rpm-build d9acb6
    """Convert a BeautifulSoup tree to a list of Element trees.
rpm-build d9acb6
rpm-build d9acb6
    Returns a list instead of a single root Element to support
rpm-build d9acb6
    HTML-like soup with more than one root element.
rpm-build d9acb6
rpm-build d9acb6
    You can pass a different Element factory through the `makeelement`
rpm-build d9acb6
    keyword.
rpm-build d9acb6
    """
rpm-build d9acb6
    root = _convert_tree(beautiful_soup_tree, makeelement)
rpm-build d9acb6
    children = root.getchildren()
rpm-build d9acb6
    for child in children:
rpm-build d9acb6
        root.remove(child)
rpm-build d9acb6
    return children
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
# helpers
rpm-build d9acb6
rpm-build d9acb6
def _parse(source, beautifulsoup, makeelement, **bsargs):
rpm-build d9acb6
    if beautifulsoup is None:
rpm-build d9acb6
        beautifulsoup = BeautifulSoup
rpm-build d9acb6
    if hasattr(beautifulsoup, "HTML_ENTITIES"):  # bs3
rpm-build d9acb6
        if 'convertEntities' not in bsargs:
rpm-build d9acb6
            bsargs['convertEntities'] = 'html'
rpm-build d9acb6
    if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"):  # bs4
rpm-build d9acb6
        if 'features' not in bsargs:
rpm-build d9acb6
            bsargs['features'] = 'html.parser'  # use Python html parser
rpm-build d9acb6
    tree = beautifulsoup(source, **bsargs)
rpm-build d9acb6
    root = _convert_tree(tree, makeelement)
rpm-build d9acb6
    # from ET: wrap the document in a html root element, if necessary
rpm-build d9acb6
    if len(root) == 1 and root[0].tag == "html":
rpm-build d9acb6
        return root[0]
rpm-build d9acb6
    root.tag = "html"
rpm-build d9acb6
    return root
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
_parse_doctype_declaration = re.compile(
rpm-build d9acb6
    r'(?:\s|[
rpm-build d9acb6
    r'(?:\s+PUBLIC)?(?:\s+(\'[^\']*\'|"[^"]*"))?'
rpm-build d9acb6
    r'(?:\s+(\'[^\']*\'|"[^"]*"))?',
rpm-build d9acb6
    re.IGNORECASE).match
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
class _PseudoTag:
rpm-build d9acb6
    # Minimal imitation of BeautifulSoup.Tag
rpm-build d9acb6
    def __init__(self, contents):
rpm-build d9acb6
        self.name = 'html'
rpm-build d9acb6
        self.attrs = []
rpm-build d9acb6
        self.contents = contents
rpm-build d9acb6
rpm-build d9acb6
    def __iter__(self):
rpm-build d9acb6
        return self.contents.__iter__()
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
def _convert_tree(beautiful_soup_tree, makeelement):
rpm-build d9acb6
    if makeelement is None:
rpm-build d9acb6
        makeelement = html.html_parser.makeelement
rpm-build d9acb6
rpm-build d9acb6
    # Split the tree into three parts:
rpm-build d9acb6
    # i) everything before the root element: document type
rpm-build d9acb6
    # declaration, comments, processing instructions, whitespace
rpm-build d9acb6
    # ii) the root(s),
rpm-build d9acb6
    # iii) everything after the root: comments, processing
rpm-build d9acb6
    # instructions, whitespace
rpm-build d9acb6
    first_element_idx = last_element_idx = None
rpm-build d9acb6
    html_root = declaration = None
rpm-build d9acb6
    for i, e in enumerate(beautiful_soup_tree):
rpm-build d9acb6
        if isinstance(e, Tag):
rpm-build d9acb6
            if first_element_idx is None:
rpm-build d9acb6
                first_element_idx = i
rpm-build d9acb6
            last_element_idx = i
rpm-build d9acb6
            if html_root is None and e.name and e.name.lower() == 'html':
rpm-build d9acb6
                html_root = e
rpm-build d9acb6
        elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):
rpm-build d9acb6
            declaration = e
rpm-build d9acb6
rpm-build d9acb6
    # For a nice, well-formatted document, the variable roots below is
rpm-build d9acb6
    # a list consisting of a single <html> element. However, the document
rpm-build d9acb6
    # may be a soup like '<meta><head><title>Hello</head><body>Hi
rpm-build d9acb6
    # all<\p>'. In this example roots is a list containing meta, head
rpm-build d9acb6
    # and body elements.
rpm-build d9acb6
    if first_element_idx is None:
rpm-build d9acb6
        pre_root = post_root = []
rpm-build d9acb6
        roots = beautiful_soup_tree.contents
rpm-build d9acb6
    else:
rpm-build d9acb6
        pre_root = beautiful_soup_tree.contents[:first_element_idx]
rpm-build d9acb6
        roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]
rpm-build d9acb6
        post_root = beautiful_soup_tree.contents[last_element_idx+1:]
rpm-build d9acb6
rpm-build d9acb6
    # Reorganize so that there is one <html> root...
rpm-build d9acb6
    if html_root is not None:
rpm-build d9acb6
        # ... use existing one if possible, ...
rpm-build d9acb6
        i = roots.index(html_root)
rpm-build d9acb6
        html_root.contents = roots[:i] + html_root.contents + roots[i+1:]
rpm-build d9acb6
    else:
rpm-build d9acb6
        # ... otherwise create a new one.
rpm-build d9acb6
        html_root = _PseudoTag(roots)
rpm-build d9acb6
rpm-build d9acb6
    convert_node = _init_node_converters(makeelement)
rpm-build d9acb6
rpm-build d9acb6
    # Process pre_root
rpm-build d9acb6
    res_root = convert_node(html_root)
rpm-build d9acb6
    prev = res_root
rpm-build d9acb6
    for e in reversed(pre_root):
rpm-build d9acb6
        converted = convert_node(e)
rpm-build d9acb6
        if converted is not None:
rpm-build d9acb6
            prev.addprevious(converted)
rpm-build d9acb6
            prev = converted
rpm-build d9acb6
rpm-build d9acb6
    # ditto for post_root
rpm-build d9acb6
    prev = res_root
rpm-build d9acb6
    for e in post_root:
rpm-build d9acb6
        converted = convert_node(e)
rpm-build d9acb6
        if converted is not None:
rpm-build d9acb6
            prev.addnext(converted)
rpm-build d9acb6
            prev = converted
rpm-build d9acb6
rpm-build d9acb6
    if declaration is not None:
rpm-build d9acb6
        try:
rpm-build d9acb6
            # bs4 provides full Doctype string
rpm-build d9acb6
            doctype_string = declaration.output_ready()
rpm-build d9acb6
        except AttributeError:
rpm-build d9acb6
            doctype_string = declaration.string
rpm-build d9acb6
rpm-build d9acb6
        match = _parse_doctype_declaration(doctype_string)
rpm-build d9acb6
        if not match:
rpm-build d9acb6
            # Something is wrong if we end up in here. Since soupparser should
rpm-build d9acb6
            # tolerate errors, do not raise Exception, just let it pass.
rpm-build d9acb6
            pass
rpm-build d9acb6
        else:
rpm-build d9acb6
            external_id, sys_uri = match.groups()
rpm-build d9acb6
            docinfo = res_root.getroottree().docinfo
rpm-build d9acb6
            # strip quotes and update DOCTYPE values (any of None, '', '...')
rpm-build d9acb6
            docinfo.public_id = external_id and external_id[1:-1]
rpm-build d9acb6
            docinfo.system_url = sys_uri and sys_uri[1:-1]
rpm-build d9acb6
rpm-build d9acb6
    return res_root
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
def _init_node_converters(makeelement):
rpm-build d9acb6
    converters = {}
rpm-build d9acb6
    ordered_node_types = []
rpm-build d9acb6
rpm-build d9acb6
    def converter(*types):
rpm-build d9acb6
        def add(handler):
rpm-build d9acb6
            for t in types:
rpm-build d9acb6
                converters[t] = handler
rpm-build d9acb6
                ordered_node_types.append(t)
rpm-build d9acb6
            return handler
rpm-build d9acb6
        return add
rpm-build d9acb6
rpm-build d9acb6
    def find_best_converter(node):
rpm-build d9acb6
        for t in ordered_node_types:
rpm-build d9acb6
            if isinstance(node, t):
rpm-build d9acb6
                return converters[t]
rpm-build d9acb6
        return None
rpm-build d9acb6
rpm-build d9acb6
    def convert_node(bs_node, parent=None):
rpm-build d9acb6
        # duplicated in convert_tag() below
rpm-build d9acb6
        try:
rpm-build d9acb6
            handler = converters[type(bs_node)]
rpm-build d9acb6
        except KeyError:
rpm-build d9acb6
            handler = converters[type(bs_node)] = find_best_converter(bs_node)
rpm-build d9acb6
        if handler is None:
rpm-build d9acb6
            return None
rpm-build d9acb6
        return handler(bs_node, parent)
rpm-build d9acb6
rpm-build d9acb6
    def map_attrs(bs_attrs):
rpm-build d9acb6
        if isinstance(bs_attrs, dict):  # bs4
rpm-build d9acb6
            attribs = {}
rpm-build d9acb6
            for k, v in bs_attrs.items():
rpm-build d9acb6
                if isinstance(v, list):
rpm-build d9acb6
                    v = " ".join(v)
rpm-build d9acb6
                attribs[k] = unescape(v)
rpm-build d9acb6
        else:
rpm-build d9acb6
            attribs = dict((k, unescape(v)) for k, v in bs_attrs)
rpm-build d9acb6
        return attribs
rpm-build d9acb6
rpm-build d9acb6
    def append_text(parent, text):
rpm-build d9acb6
        if len(parent) == 0:
rpm-build d9acb6
            parent.text = (parent.text or '') + text
rpm-build d9acb6
        else:
rpm-build d9acb6
            parent[-1].tail = (parent[-1].tail or '') + text
rpm-build d9acb6
rpm-build d9acb6
    # converters are tried in order of their definition
rpm-build d9acb6
rpm-build d9acb6
    @converter(Tag, _PseudoTag)
rpm-build d9acb6
    def convert_tag(bs_node, parent):
rpm-build d9acb6
        attrs = bs_node.attrs
rpm-build d9acb6
        if parent is not None:
rpm-build d9acb6
            attribs = map_attrs(attrs) if attrs else None
rpm-build d9acb6
            res = etree.SubElement(parent, bs_node.name, attrib=attribs)
rpm-build d9acb6
        else:
rpm-build d9acb6
            attribs = map_attrs(attrs) if attrs else {}
rpm-build d9acb6
            res = makeelement(bs_node.name, attrib=attribs)
rpm-build d9acb6
rpm-build d9acb6
        for child in bs_node:
rpm-build d9acb6
            # avoid double recursion by inlining convert_node(), see above
rpm-build d9acb6
            try:
rpm-build d9acb6
                handler = converters[type(child)]
rpm-build d9acb6
            except KeyError:
rpm-build d9acb6
                pass
rpm-build d9acb6
            else:
rpm-build d9acb6
                if handler is not None:
rpm-build d9acb6
                    handler(child, res)
rpm-build d9acb6
                continue
rpm-build d9acb6
            convert_node(child, res)
rpm-build d9acb6
        return res
rpm-build d9acb6
rpm-build d9acb6
    @converter(Comment)
rpm-build d9acb6
    def convert_comment(bs_node, parent):
rpm-build d9acb6
        res = html.HtmlComment(bs_node)
rpm-build d9acb6
        if parent is not None:
rpm-build d9acb6
            parent.append(res)
rpm-build d9acb6
        return res
rpm-build d9acb6
rpm-build d9acb6
    @converter(ProcessingInstruction)
rpm-build d9acb6
    def convert_pi(bs_node, parent):
rpm-build d9acb6
        if bs_node.endswith('?'):
rpm-build d9acb6
            # The PI is of XML style () but BeautifulSoup
rpm-build d9acb6
            # interpreted it as being SGML style (). Fix.
rpm-build d9acb6
            bs_node = bs_node[:-1]
rpm-build d9acb6
        res = etree.ProcessingInstruction(*bs_node.split(' ', 1))
rpm-build d9acb6
        if parent is not None:
rpm-build d9acb6
            parent.append(res)
rpm-build d9acb6
        return res
rpm-build d9acb6
rpm-build d9acb6
    @converter(NavigableString)
rpm-build d9acb6
    def convert_text(bs_node, parent):
rpm-build d9acb6
        if parent is not None:
rpm-build d9acb6
            append_text(parent, unescape(bs_node))
rpm-build d9acb6
        return None
rpm-build d9acb6
rpm-build d9acb6
    return convert_node
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
# copied from ET's ElementSoup
rpm-build d9acb6
rpm-build d9acb6
try:
rpm-build d9acb6
    from html.entities import name2codepoint  # Python 3
rpm-build d9acb6
except ImportError:
rpm-build d9acb6
    from htmlentitydefs import name2codepoint
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
handle_entities = re.compile(r"&(\w+);").sub
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
try:
rpm-build d9acb6
    unichr
rpm-build d9acb6
except NameError:
rpm-build d9acb6
    # Python 3
rpm-build d9acb6
    unichr = chr
rpm-build d9acb6
rpm-build d9acb6
rpm-build d9acb6
def unescape(string):
rpm-build d9acb6
    if not string:
rpm-build d9acb6
        return ''
rpm-build d9acb6
    # work around oddities in BeautifulSoup's entity handling
rpm-build d9acb6
    def unescape_entity(m):
rpm-build d9acb6
        try:
rpm-build d9acb6
            return unichr(name2codepoint[m.group(1)])
rpm-build d9acb6
        except KeyError:
rpm-build d9acb6
            return m.group(0)  # use as is
rpm-build d9acb6
    return handle_entities(unescape_entity, string)