html_doc="""
<html>
<head></head>
<body>
<ul class="navigation"></ul>
</body>
</html>
"""
link_doc="""
<p>
<li><a href="http://example.com/elsie" id="link1">Elsie</a></li>
<li><a href="http://example.com/lacie" id="link2">Lacie</a></li>
<li><a href="http://example.com/tillie" id="link3">Tillie</a></li>
</p>
"""
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()
I have two simple documents like this. What I'd like to do is add some links between <ul class="navigation">
and write them to 3 files.
But also I'd like to add class attributes active
to the <li>
element depending on file order. For example 0.html should be like this:
<ul class="navigation">
<li class="active">
<a href="http://example.com/elsie" id="link1">
Elsie
</a>
</li>
<li>
<a href="http://example.com/lacie" id="link2">
Lacie
</a>
</li>
<li>
<a href="http://example.com/tillie" id="link3">
Tillie
</a>
</li>
</ul>
1.html would be like this etc.
<ul class="navigation">
<li>
<a href="http://example.com/elsie" id="link1">
Elsie
</a>
</li>
<li class="active">
<a href="http://example.com/lacie" id="link2">
Lacie
</a>
</li>
<li>
<a href="http://example.com/tillie" id="link3">
Tillie
</a>
</li>
</ul>
How can I do that?