如何在Python中生成HTML文本的目录?

Lea*_*orm 1 html python tableofcontents

假设我有一些HTML代码,就像这样(从Markdown或Textile或其他东西生成):

<h1>A header</h1>
<p>Foo</p>
<h2>Another header</h2>
<p>More content</p>
<h2>Different header</h2>
<h1>Another toplevel header
<!-- and so on -->
Run Code Online (Sandbox Code Playgroud)

我怎么能用Python为它生成一个目录?

Ign*_*ams 6

使用HTML解析器(如lxmlBeautifulSoup)查找所有标题元素.

  • @van:BeautifulSoup是纯Python但不兼容3.x.lxml很好,但需要一个C编译器来构建. (3认同)