如何在 Python 中为 HTML 文本生成目录? [英] How do I generate a table of contents for HTML text in Python?

查看:29
本文介绍了如何在 Python 中为 HTML 文本生成目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Assume that I have some HTML code, like this (generated from Markdown or Textile or something):

<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 为其生成目录?

How could I generate a table of contents for it using Python?

推荐答案

使用 HTML 解析器,例如 lxmlBeautifulSoup 以查找所有标题元素.

Use an HTML parser such as lxml or BeautifulSoup to find all header elements.

这篇关于如何在 Python 中为 HTML 文本生成目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆