如何使用Python和BeautifulSoup添加HTML属性
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">
之间添加一些链接,并把它们写入三个文件中。
另外,我还想根据文件的顺序给 <li>
元素添加一个叫 active
的类属性。比如说,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>
我该怎么做呢?
1 个回答
1
编辑: 我添加了一种更好的插入链接的方法。希望这对你有帮助!
编辑 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()