Say that I have this piece of HTML:
<p>This text is my <a href="#">text</a><p>
How do I replace the first "text" with an anchor element, so the result becomes:
<p>This <a href="#">text</a> is my <a href="#">text</a><p>
I basically want to replace a substring in a NavigableString with a Tag.
You can get the text of NavigableString, modify it, build new object model from modified text and then replace old NavigableString with this object model:
data = '<p>This text is my <a href="#">text</a><p>'
soup = BeautifulSoup(data)
original_string = soup.p.contents[0]
new_text = unicode(original_string).replace(' text ', '<a href="#">text</a>')
original_string.replaceWith(BeautifulSoup(text))
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