How can I insert a new tag into a BeautifulSoup object?

Jay Gattuso picture Jay Gattuso · Jan 25, 2014 · Viewed 36.5k times · Source

Trying to get my head around html construction with BS.

I'm trying to insert a new tag:

self.new_soup.body.insert(3, """<div id="file_history"></div>""")   

when I check the result, I get:

&lt;div id="file_histor"y&gt;&lt;/div&gt;

So I'm inserting a string that being sanitised for websafe html..

What I expect to see is:

<div id="file_history"></div>

How do I insert a new div tag in position 3 with the id file_history?

Answer

Guy Gavriely picture Guy Gavriely · Jan 25, 2014

See the documentation on how to append a tag:

soup = BeautifulSoup("<b></b>")
original_tag = soup.b

new_tag = soup.new_tag("a", href="http://www.example.com")
original_tag.append(new_tag)
original_tag
# <b><a href="http://www.example.com"></a></b>

new_tag.string = "Link text."
original_tag
# <b><a href="http://www.example.com">Link text.</a></b>