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()
我有两个像这样的简单文件。我想做的是在<ul class="navigation">
之间添加一些链接,并将它们写入3个文件。
但我还想根据文件顺序将类属性active
添加到<li>
元素。例如 0.html 应该是这样的:
<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 就像这样。
<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>
我该怎么做?
答案 0 :(得分:2)
编辑:我添加了一种更好的插入链接的方法。我希望这有帮助!
编辑x2 :现在应该可以使用了:
添加链接:
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
要添加您的class =“active”,请将此最后一个for循环替换为:
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()