title: How to add html attributes using python and BeautifulSoup
body: <pre><code>html_doc="""
  &lt;html&gt;
      &lt;head&gt;&lt;/head&gt;
      &lt;body&gt;
          &lt;ul class="navigation"&gt;&lt;/ul&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  """
  link_doc="""
  &lt;p&gt;
  &lt;li&gt;&lt;a href="http://example.com/elsie" id="link1"&gt;Elsie&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://example.com/lacie" id="link2"&gt;Lacie&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://example.com/tillie" id="link3"&gt;Tillie&lt;/a&gt;&lt;/li&gt;
  &lt;/p&gt;
  """
  from bs4 import BeautifulSoup
  soup = BeautifulSoup(html_doc)
  link = BeautifulSoup(link_doc)
  
  navigation = soup.find_all("ul", {"class" : "navigation"})
  links = link.find_all('li')
  
  for i in range(0,3): # assume I would like to write to 3 files
      for n in range(len(links)):
          navigation[0].append(links[n])
      output = navigation[0].prettify(formatter=None)
      file = open(str(i) + '.html', 'w')
      file.write(output)
      file.close()
      navigation[0].clear()    
  </code></pre>
  
  <p>I have two simple documents like this. What I'd like to do is add some links between <code>&lt;ul class="navigation"&gt;</code> and write them to 3 files. </p>
  
  <p>But also I'd like to add class attributes <code>active</code> to the <code>&lt;li&gt;</code> element depending on file order. For example <em>0.html</em> should be like this:</p>
  
  <pre><code>&lt;ul class="navigation"&gt;
   &lt;li class="active"&gt;
    &lt;a href="http://example.com/elsie" id="link1"&gt;
     Elsie
    &lt;/a&gt;
   &lt;/li&gt;
   &lt;li&gt;
    &lt;a href="http://example.com/lacie" id="link2"&gt;
     Lacie
    &lt;/a&gt;
   &lt;/li&gt;
   &lt;li&gt;
    &lt;a href="http://example.com/tillie" id="link3"&gt;
     Tillie
    &lt;/a&gt;
   &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p><em>1.html</em> would be like this etc.</p>
  
  <pre><code>&lt;ul class="navigation"&gt;
   &lt;li&gt;
    &lt;a href="http://example.com/elsie" id="link1"&gt;
     Elsie
    &lt;/a&gt;
   &lt;/li&gt;
   &lt;li class="active"&gt;
    &lt;a href="http://example.com/lacie" id="link2"&gt;
     Lacie
    &lt;/a&gt;
   &lt;/li&gt;
   &lt;li&gt;
    &lt;a href="http://example.com/tillie" id="link3"&gt;
     Tillie
    &lt;/a&gt;
   &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>How can I do that?</p>