Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeautifulSoup: How to replace value in an element with an element tag?

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.

like image 577
zer0stimulus Avatar asked Apr 20 '12 01:04

zer0stimulus


1 Answers

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))
like image 144
vvzh Avatar answered Sep 22 '22 13:09

vvzh