1

次のような 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 -->

Python を使用して目次を生成するにはどうすればよいですか?

4

2 に答える 2

6

lxmlBeautifulSoupなどの HTML パーサーを使用して、すべてのヘッダー要素を検索します。

于 2010-02-05T20:41:09.480 に答える
3

lxml と xpath を使用した例を次に示します。

from lxml import etree
doc = etree.parse("test.xml")
for node in doc.xpath('//h1|//h2|//h3|//h4|//h5'):
    print node.tag, node.text
于 2010-02-05T22:26:59.217 に答える