如何用BeautifulSoup更改标签名?
我正在使用Python和BeautifulSoup来解析一个HTML文档。
现在我需要把文档中所有的 <h2 class="someclass">
元素,替换成 <h1 class="someclass">
。
我该怎么做才能只改变标签的名字,而不改变文档中的其他内容呢?
3 个回答
0
from BeautifulSoup import BeautifulSoup, Tag
soup = BeautifulSoup("<h2 class="someclass">TEXTHERE</h2>")
tag = Tag(soup, "h1", [("class", "someclass")])
tag.insert(0, "TEXTHERE")
soup.h2.replaceWith(tag)
print soup
# <h1 class="someclass">TEXTHERE</h1>
3
就是这样:
tag.name = 'new_name'
37
我不知道你是怎么访问 tag
的,但下面这个方法对我有效:
import BeautifulSoup
if __name__ == "__main__":
data = """
<html>
<h2 class='someclass'>some title</h2>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
<li>Vestibulum auctor dapibus neque.</li>
</ul>
</html>
"""
soup = BeautifulSoup.BeautifulSoup(data)
h2 = soup.find('h2')
h2.name = 'h1'
print soup
执行 print soup
命令的输出结果是:
<html>
<h1 class='someclass'>some title</h1>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
<li>Vestibulum auctor dapibus neque.</li>
</ul>
</html>
你可以看到,h2
变成了 h1
。而文档中的其他内容没有发生变化。我使用的是 Python 2.6 和 BeautifulSoup 3.2.0。
如果你有多个 h2
,想要全部修改,可以简单地这样做:
soup = BeautifulSoup.BeautifulSoup(your_data)
while True:
h2 = soup.find('h2')
if not h2:
break
h2.name = 'h1'