Jay Gattuso Jay Gattuso - 5 months ago 31
Python Question

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

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

Use the factory method to create new elements:

new_tag = self.new_soup.new_tag('div', id='file_history')

and insert it:

self.new_soup.body.insert(3, new_tag)
Comments