Beautiful Soup – insert Method


Beautiful Soup – insert() Method



”;


Method Description

The insert() method in Beautiful Soup add an element at the given position in a the list of children of a Tag element. The insert() method in Beautiful Soup behaves similar to insert() on a Python list object.

Syntax


insert(position, child)

Parameters

  • position − The position at which the new PageElement should be inserted.

  • child − A PageElement to be inserted.

Return Type

The insert() method doesn”t return any new object.

Example 1

In the following example, a new string is added to the <b> tag at position 1. The resultant parsed document shows the result.


from bs4 import BeautifulSoup, NavigableString

markup = ''<b>Excellent </b><u>from TutorialsPoint</u>''
soup = BeautifulSoup(markup, ''html.parser'')
tag = soup.b

tag.insert(1, "Tutorial ")
print (soup.prettify())

Output


<b>
   Excellent
   Tutorial
</b>
<u>
   from TutorialsPoint
</u>

Example 2

In the following example, the insert() method is used to successively insert strings from a list to a <p> tag in HTML markup.


from bs4 import BeautifulSoup, NavigableString

markup = ''<p>Excellent Tutorials from TutorialsPoint</p>''
soup = BeautifulSoup(markup, ''html.parser'')
langs = [''Python'', ''Java'', ''C'']
i=0
for lang in langs:
   i+=1
   tag = soup.new_tag(''p'')
   tag.string = lang
   soup.p.insert(i, tag)


print (soup.prettify())

Output


<p>
   Excellent Tutorials from TutorialsPoint
   <p>
   Python
   </p>
   <p>
      Java
   </p>
   <p>
      C
   </p>
</p>

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *