2011-03-13 71 views
10

我正在使用python + BeautifulSoup來解析HTML文檔。如何使用BeautifulSoup更改標籤名稱?

現在我需要用一個HTML文檔中的所有<h2 class="someclass">元素替換爲<h1 class="someclass">

如何更改標籤名稱,而不更改文檔中的其他內容?

回答

14

我不知道你是如何訪問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' 
+0

不知道爲什麼它以前沒有爲我工作過。感謝你的回答。 – daphshez 2011-03-13 15:34:06

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> 
+0

我認爲這將刪除的所有內容h2標籤。我只想替換標籤名稱並保留其他所有內容。 – daphshez 2011-03-13 15:35:10

1

這只是:

tag.name = 'new_name'