Home Python function to replace all instances of a tag with another

# Python function to replace all instances of a tag with another

user1327
1#
user1327 Published in April 22, 2018, 3:05 am
 How would I go about writing a function (with BeautifulSoup or otherwise) that would replace all instances of one HTML tag with another. For example: text = "

this is some text

with some tagsthat I wouldlike to replace" new_text = replace_tags(text, "bad", "p") print(new_text) # "

this is some text

with some tags

that I would

like to replace

"  I tried this, but preserving the attributes of each tag is a challenge: def replace_tags(string, old_tag, new_tag): soup = BeautifulSoup(string, "html.parser") nodes = soup.findAll(old_tag) for node in nodes: new_content = BeautifulSoup("<{0}>{1}
 You need to login account before you can post.
Processed in 0.304388 second(s) , Gzip On .