如何用BeautifulSoup更改标签名称?

时间:2011-03-13 11:53:55

标签: python html-parsing beautifulsoup

我使用python + BeautifulSoup来解析HTML文档。

现在,我需要使用<h2 class="someclass">替换HTML文档中的所有<h1 class="someclass">元素。

如何在不更改文档中的任何其他内容的情况下更改标记名称?

3 个答案:

答案 0 :(得分:19)

我不知道您是如何访问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'

答案 1 :(得分:1)

只是:

tag.name = 'new_name'

答案 2 :(得分:0)

来自BeautifulSoup docs

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>