如何使用BeautifulSoup更改标签名称?
问题描述:
我正在使用python + BeautifulSoup来解析HTML文档。如何使用BeautifulSoup更改标签名称?
现在我需要用一个HTML文档中的所有<h2 class="someclass">
元素替换为<h1 class="someclass">
。
如何更改标签名称,而不更改文档中的其他内容?
答
我不知道你是如何访问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'
答
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>
+0
我认为这将删除的所有内容h2标签。我只想替换标签名称并保留其他所有内容。 – daphshez 2011-03-13 15:35:10
答
这只是:
tag.name = 'new_name'
不知道为什么它以前没有为我工作过。感谢你的回答。 – daphshez 2011-03-13 15:34:06