如何用 BeautifulSoup 更改标签名称?

Posted

技术标签:

【中文标题】如何用 BeautifulSoup 更改标签名称?【英文标题】:How to change tag name with BeautifulSoup? 【发布时间】:2011-07-14 10:27:52 【问题描述】:

我正在使用 python + BeautifulSoup 来解析 html 文档。

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

如何更改标签名称,而不更改文档中的任何其他内容?

【问题讨论】:

【参考方案1】:

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

【讨论】:

不知道为什么它以前对我不起作用。感谢您的回答。【参考方案2】:

只是:

tag.name = 'new_name'

【讨论】:

【参考方案3】:

来自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>

【讨论】:

我认为这会删除 h2 标签的所有内容。我只想替换标签名称并保持其他所有内容不变。

以上是关于如何用 BeautifulSoup 更改标签名称?的主要内容,如果未能解决你的问题,请参考以下文章

已知如何用标签值更改 UIButton 背景图像?

如何用我从文本框中得到的号码更改证书的名称

如何用 Beautifulsoup 解析“数据文本”? [复制]

如何用beautifulsoup提取网页某个部分的所有链接? [复制]

如何用 BeautifulSoup 抓取 Instagram

如何用 BeautifulSoup 等一秒钟来保存汤元素以让页面中的元素加载完成