Created
November 7, 2011 20:44
-
-
Save haldean/1346114 to your computer and use it in GitHub Desktop.
Generate HTML Table of Contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gen_toc(html, ignore_h1_in_toc=False): | |
if ignore_h1_in_toc: | |
first_level = 2 | |
else: | |
first_level = 1 | |
soup = BeautifulSoup.BeautifulSoup(html) | |
headers = soup.findAll(re.compile('^h[%d-6]' % first_level)) | |
output = [] | |
for header in headers: | |
hid = header.get('id') | |
title = header.text | |
level = int(header.name[-1]) | |
if hid: | |
output.append('%s<a href="#%s">%s</a>' % ( | |
(level - first_level) * 4 * ' ', hid, title)) | |
else: | |
output.append('%s%s' % ((level - first_level) * 4 * ' ', title)) | |
return '<br/>\n'.join(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment