Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not

    Args:
        tag: a bs4.element.Tag

    Returns:"
        bs4.element.Tag: A bs4 tag representing a full html document
775731
def create_html_from_fragment(tag):
    

    try:
        assert isinstance(tag, bs4.element.Tag)
    except AssertionError:
        raise TypeError
    try:
        assert tag.find_all('body') == []
    except AssertionError:
        raise ValueError

    soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser')
    soup.body.append(tag)
    return soup
881211
def _init_tag(self, tag):
        
        self._element = tag

        self._parseIsTag()
        self._parseIsComment()

        if not self._istag or self._iscomment:
            self._tagname = self._element
        else:
            self._parseTagName()

        if self._iscomment or not self._istag:
            return

        self._parseIsEndTag()
        self._parseIsNonPairTag()

        if self._istag and (not self._isendtag) or "=" in self._element:
            self._parseParams()
1285223
function toElement(str) {
    if (!range && doc.createRange) {
        range = doc.createRange();
        range.selectNode(doc.body);
    }

    var fragment;
    if (range && range.createContextualFragment) {
        fragment = range.createContextualFragment(str);
    } else {
        fragment = doc.createElement('body');
        fragment.innerHTML = str;
    }
    return fragment.childNodes[0];
}
421525
def jinja_fragment_extension(tag, endtag=None, name=None, tag_only=False, allow_args=True, callblock_args=None):
    
    if endtag is None:
        endtag = "end" + tag

    def decorator(f):
        def parse(self, parser):
            lineno = parser.stream.next().lineno
            args = []
            kwargs = []
            if allow_args:
                args, kwargs = parse_block_signature(parser)

            call = self.call_method("support_method", args, kwargs, lineno=lineno)
            if tag_only:
                return nodes.Output([call], lineno=lineno)

            call_args = []
            if callblock_args is not None:
                for arg in callblock_args:
                    call_args.append(nodes.Name(arg, 'param', lineno=lineno))

            body = parser.parse_statements(['name:' + endtag], drop_needle=True)
            return nodes.CallBlock(call, call_args, [], body, lineno=lineno)

        def support_method(self, *args, **kwargs):
            return f(*args, **kwargs)

        attrs = {"tags": set([tag]), "parse": parse, "support_method": support_method}
        return type(name or f.__name__, (Extension,), attrs)

    return decorator
1276158
def _buildElementTree(self,):
        
        t_binder = ctree.Element(self.name)

        for k,v in self.__dict__.items():
            if k not in ('name', 'urls', 'inputs', 'paging') and v :
                t_binder.set(k,v)

        self.etree = t_binder
        return t_binder
72708
def handle_endtag(self, tag):
        
        if tag in PARENT_ELEMENTS:
            self.current_parent_element['tag'] = ''
            self.current_parent_element['attrs'] = ''

        if tag == 'li':
            self.parsing_li = True
        if tag != 'br':
            self.cleaned_html += '</{}>'.format(tag)
1243948
def to_xml(self, root):
        '''
        
        '''
        if not len(self.__custom_elements):
            return

        for uri, tags in self.__custom_elements.items():
            prefix, url = uri.split(":", 1)
            for name, value in tags.items():
                self.__createElementNS(root, url, prefix + ":" + name, value)

        return root
868316
def process_tag(node):
    
    text = ''

    exceptions = ['table']

    for element in node.children:
        if isinstance(element, NavigableString):
            text += element
        elif not node.name in exceptions:
            text += process_tag(element)

    try:
        convert_fn = globals()["convert_%s" % node.name.lower()]
        text = convert_fn(node, text)

    except KeyError:
        pass

    return text
850634
def parse_html(html: str, parser: FragmentParser = None) -> Node:
    
    parser = parser or FragmentParser()
    parser.feed(html)
    return parser.root
910764
def render_tag(self, context, kwargs, nodelist):
        ''''''
        # load configuration from passed options
        self.load_configuration(**kwargs)

        # get request from context
        request = context['request']

        # get full path from request
        self.full_path = request.get_full_path()

        # render content of template tag
        context.push()
        content = nodelist.render(context)
        context.pop()

        # check content for "active" urls
        content = render_content(
            content,
            full_path=self.full_path,
            parent_tag=self.parent_tag,
            css_class=self.css_class,
            menu=self.menu,
            ignore_params=self.ignore_params,
        )

        return content
377630
def html_to_text(html_string):
    
    # create a valid html document from string
    # beware that it inserts <hmtl> <body> and <p> tags
    # where needed
    html_tree = html.document_fromstring(html_string)

    # handle header tags
    for h in html_tree.cssselect("h1, h2, h3, h4, h5, h6"):
        # add two newlines after a header tag
        h.text = h.text + '\n\n'

    # handle links
    # find all a tags starting from the root of the document //
    # and replace the link with (link)
    for a in html_tree.xpath("//a"):
        href = a.attrib['href']
        a.text = a.text + " (" + href + ")"

    # handle paragraphs
    for p in html_tree.xpath("//p"):
        # keep the tail if there is one
        # or add two newlines after the text if there is no tail
        p.tail = p.tail if p.tail else "\n\n"

    # handle breaks
    for br in html_tree.xpath("//br"):
        # add a newline and then the tail (remaining text after the <br/> tag)
        # or add a newline only if there is no tail
        # http://stackoverflow.com/questions/18660382/how-can-i-preserve-br-as-newlines-with-lxml-html-text-content-or-equivalent?rq=1
        br.tail = "\n" + br.tail if br.tail else "\n"

    return html_tree.text_content()
254997
public static Document parseBodyFragment(String bodyHtml, String baseUri) {
        Document doc = Document.createShell(baseUri);
        Element body = doc.body();
        List<Node> nodeList = parseFragment(bodyHtml, body, baseUri);
        Node[] nodes = nodeList.toArray(new Node[0]); // the node list gets modified when re-parented
        for (int i = nodes.length - 1; i > 0; i--) {
            nodes[i].remove();
        }
        for (Node node : nodes) {
            body.appendChild(node);
        }
        return doc;
    }
483211
def _buildElementTree(self,):
        

        t_paging = ctree.Element('paging')
        t_paging.set('model', self.model)
        for key in self.__dict__.keys():
            if key != 'model':
                t_tag = ctree.SubElement(t_paging, key)
                for item in self.__dict__[key].items():
                    t_tag.set(*item)

        self.etree = t_paging
        return  t_paging
982764
def leaf_div_elements_into_paragraphs(document):
    
    for element in document.iter(tag="div"):
        child_tags = tuple(n.tag for n in element.getchildren())
        if "div" not in child_tags and "p" not in child_tags:
            logger.debug(
                "Changing leaf block element <%s> into <p>", element.tag)
            element.tag = "p"

    return document
394284
def element(self, tag_path, test=None, **attributes):
        """"""
        xpath = tag_path
        tests = ["@%s='%s'" % (k, attributes[k]) for k in attributes]
        if test is not None:
            tests.insert(0, test)
        if len(tests) > 0:
            xpath += "[%s]" % ' and '.join(tests)
        e = self.find(self.root, xpath)
        if e is None:
            tag = tag_path.split('/')[-1].split('[')[0]
            tagname = tag.split(':')[-1]
            if ':' in tag:
                nstag = tag.split(':')[0]
                tag = "{%s}%s" % (self.NS[nstag], tagname)
            e = etree.Element(tag, **attributes)
        return e
252973
def _in_tag(self, tagname, attributes=None):
        
        node = self.cur_node
        while not node is None:
            if node.tag == tagname:
                if attributes and node.attrib == attributes:
                    return True

                elif attributes:
                    return False

                return True

            node = node.getparent()
        return False
923907
def render_tag(tag, attrs=None, content=None, close=True):
    
    builder = "<{tag}{attrs}>{content}"
    if content or close:
        builder += "</{tag}>"
    return format_html(
        builder,
        tag=tag,
        attrs=mark_safe(flatatt(attrs)) if attrs else "",
        content=text_value(content),
    )