(html_doc, toc)
Build table of contents.
Build table of contents.
Build table of contents .
def _maketoc(html_doc, toc):
    """Build table of contents."""
    parser = etree.HTMLParser()
    doc = etree.parse(html_doc, parser)
    last = -1
    toc.write(u'<nav class="toc">\n')
    toc.write(u'    <h2 id="toc">Table of Contents</h2>\n')
    for node in doc.xpath('//h2|//h3|//h4'):
        level = int(node.tag[1])
        node_id = node.get('id')
        if last == -1:
            last += level
            first = last
        node.tag = 'a'
        node.attrib.clear()
        if node_id:
            node.set('href', '#' + node_id)
        if level-last < 0:
            toc.write(u'</li>\n')
            for i in range((last-level), 0, -1):
                toc.write(u'    '*((level+i-1)*2+1) + '</ul>\n')
                toc.write(u'    '*(level+i-1)*2 + '</li>\n')
        elif level-last > 0:
            toc.write(u'\n')
            for i in range(level-last, 0, -1):
                toc.write(u'    '*((level-i)*2+1) + '<ul>\n')
        else:
            toc.write(u'</li>\n')
        toc.write(u'    '*(level*2) + u'<li>' + etree.tostring(node).strip().decode('utf-8'))
        last = level
    toc.write(u'</li>\n')
    while level > first:
        toc.write(u'    '*(level*2-1) + '</ul>\n')
        level -= 1
    toc.write(u'</nav>\n')
def _maketoc ( html_doc , toc ) : parser = etree . HTMLParser ( ) doc = etree . parse ( html_doc , parser ) last = - 1 toc . write ( u'<nav class="toc">\n' ) toc . write ( u'    <h2 id="toc">Table of Contents</h2>\n' ) for node in doc . xpath ( '//h2|//h3|//h4' ) : level = int ( node . tag [ 1 ] ) node_id = node . get ( 'id' ) if last == - 1 : last += level first = last node . tag = 'a' node . attrib . clear ( ) if node_id : node . set ( 'href' , '#' + node_id ) if level - last < 0 : toc . write ( u'</li>\n' ) for i in range ( ( last - level ) , 0 , - 1 ) : toc . write ( u'    ' * ( ( level + i - 1 ) * 2 + 1 ) + '</ul>\n' ) toc . write ( u'    ' * ( level + i - 1 ) * 2 + '</li>\n' ) elif level - last > 0 : toc . write ( u'\n' ) for i in range ( level - last , 0 , - 1 ) : toc . write ( u'    ' * ( ( level - i ) * 2 + 1 ) + '<ul>\n' ) else : toc . write ( u'</li>\n' ) toc . write ( u'    ' * ( level * 2 ) + u'<li>' + etree . tostring ( node ) . strip ( ) . decode ( 'utf-8' ) ) last = level toc . write ( u'</li>\n' ) while level > first : toc . write ( u'    ' * ( level * 2 - 1 ) + '</ul>\n' ) level -= 1 toc . write ( u'</nav>\n' )