Last active
November 3, 2022 09:00
-
-
Save cbcafiero/c363006a36672d6803cbdee836af97ef to your computer and use it in GitHub Desktop.
Easy multiple search and replace by tag and attribute with BeautifulSoup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Sometimes you want to make several different replacements. Search by tag with | |
optional attributes. Replace with tag with optional attributes. | |
Thank you to Dan @ University of Exeter for bug fix | |
""" | |
from bs4 import BeautifulSoup | |
REPLACEMENTS = [('b', {}, 'strong', {}), | |
('u', {}, 'span', {'class': 'underline'}), | |
('i', {}, 'em', {}), | |
('font', {'size': '6'}, 'span', {'style': 'font-size:1.5em'})] | |
def replace_tags(html, replacements=REPLACEMENTS): | |
soup = BeautifulSoup(html, 'html.parser') | |
for tag, search_attribs, new_tag, new_attribs in replacements: | |
for node in soup.find_all(tag, search_attribs): | |
replacement = soup.new_tag(new_tag, **new_attribs) | |
replacement.string = node.string | |
node.replace_with(replacement) | |
return str(soup) | |
if __name__ == "__main__": | |
my_html = """<html><body><p><b>I am strong</b> and | |
<i>I am emphasized</i> and <u>I am underlined</u> and | |
<font size="6">I am bigger than everyone else</font> | |
</p></body></html>""" | |
revised = replace_tags(my_html, REPLACEMENTS) | |
print(revised) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment