Skip to content

Instantly share code, notes, and snippets.

@msalvadores
Created March 13, 2011 13:08
Show Gist options
  • Save msalvadores/868074 to your computer and use it in GitHub Desktop.
Save msalvadores/868074 to your computer and use it in GitHub Desktop.
How to change tag name with BeautifulSoup.
"""
author: Manuel Salvadores (msalvadores@gmail.com)
Code sample in answer from Stack Overflow:
http://stackoverflow.com/questions/5289189/how-to-change-tag-name-with-beautifulsoup/5289523#5289523
"""
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
@msalvadores
Copy link
Author

to change them all ...

soup = BeautifulSoup.BeautifulSoup(your_data)
while True: 
    h2 = soup.find('h2')
    if not h2:
        break
    h2.name = 'h1'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment