title: Generate a table of contents from HTML with Python
body: <p>I'm trying to generate a table of contents from a block of HTML (not a complete file - just content) based on its <code>&lt;h2&gt;</code> and <code>&lt;h3&gt;</code> tags.</p>
  
  <p>My plan so far was to:</p>
  
  <ul>
  <li><p>Extract a list of headers using <code>beautifulsoup</code></p></li>
  <li><p>Use a regex on the content to place anchor links before/inside the header tags (so the user can click on the table of contents) -- There might be a method for replacing inside <code>beautifulsoup</code>?</p></li>
  <li><p>Output a nested list of links to the headers in a predefined spot.</p></li>
  </ul>
  
  <p>It sounds easy when I say it like that, but it's proving to be a bit of a pain in the rear.</p>
  
  <p>Is there something out there that does all this for me in one go so I don't waste the next couple of hours reinventing the wheel?</p>
  
  <p>A example:</p>
  
  <pre><code>&lt;p&gt;This is an introduction&lt;/p&gt;
  
  &lt;h2&gt;This is a sub-header&lt;/h2&gt;
  &lt;p&gt;...&lt;/p&gt;
  
  &lt;h3&gt;This is a sub-sub-header&lt;/h3&gt;
  &lt;p&gt;...&lt;/p&gt;
  
  &lt;h2&gt;This is a sub-header&lt;/h2&gt;
  &lt;p&gt;...&lt;/p&gt;
  </code></pre>