Reputation:
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?
Upvotes: 1
Views: 4932
Reputation: 59974
EDIT: I added a much better way of inserting a link. I hope this helps!
edit x2: This should work now:
Adding links in:
from bs4 import BeautifulSoup
html = '<ul class="navigation"> foo <i>hi</i> bar</ul>'
soup = BeautifulSoup(html)
original_tag = soup.ul
new_tag = soup.new_tag('a', href='http://www.example.com')
new_tag.insert(0, 'Text!')
original_tag.append(new_tag)
print original_tag
# Prints:
# <ul class="navigation"> foo <i>hi</i> bar<a href="http://www.example.com">Text!</a></ul>
# If you don't want it to go to the last bit of the tag all the time,
# use original_tag.insert(). Here's a link to the documentation about it:
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#insert
For adding your class="active", replace your last for loop with this:
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)
soup2 = BeautifulSoup(output)
mylist = soup2.find_all('li')
mylist[i]['class'] = 'active'
filee = open(str(i) + '.html', 'w') # I changed it to filee to avoid confusion with the file function
filee.write(str(soup2))
filee.close()
navigation[0].clear()
Upvotes: 1