Suppose i have
text = """ <a href = 'http://www.crummy.com/software'>Hello There</a>"""
I want to replace the a hrefs and /a with just put a space (" "). In its place. BTW its a BeautifulSoup.BeautifulSoup Class. So normal .replace wouldn't work.
I want text to be just
""" Hello There """
Notice the space after and before "Hello There".
To replace a tag in Beautful Soup, find the element then call its replace_with method passing in either a string or tag.
If the text and the string to replace is simple then use str. replace().
You can use replaceWith()
(or replace_with()
):
from bs4 import BeautifulSoup
soup = BeautifulSoup("""
<html>
<body>
<a href = 'http://www.crummy.com/software'>Hello There</a>
</body>
</html>
""")
for a in soup.findAll('a'):
a.replaceWith(" %s " % a.string)
print soup
prints:
<html><body>
Hello There
</body></html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With