Beautiful Soup - insert_after() Method



Method Description

The insert_after() method in Beautiful soup inserts tags or strings immediately after something else in the parse tree. The inserted element becomes the immediate successor of this one. The inserted element can be a tag or a string.

Syntax

insert_after(*args)

Parameters

  • args − One or more elements, may be tag or a string.

Return Value

This insert_after() method doesn't return any new object.

Example 1

Following code inserts a string "Python" after the first <b> tag.

from bs4 import BeautifulSoup

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

tag.insert_after("Python ")
print (soup.prettify())

Output

<p>
   An
   <b>
      Excellent
   </b>
   Python
   Tutorial
   <u>
      from TutorialsPoint
   </u>
</p>

Example 2

You can also insert a tag before another tag. Take a look at this example.

from bs4 import BeautifulSoup, NavigableString

markup = '<P>Excellent <b>Tutorial</b> from TutorialsPoint</p>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b
tag1 = soup.new_tag('b')
tag1.string = "on Python "
tag.insert_after(tag1)
print (soup.prettify())

Output

<p>
   Excellent
   <b>
      Tutorial
   </b>
   <b>
      on Python
   </b>
   from TutorialsPoint
</p>

Example 3

Multiple tags or strings can be inserted after a certain tags.

from bs4 import BeautifulSoup, NavigableString

markup = '<P>Excellent <b>Tutorials</b> from TutorialsPoint</p>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.p
tag1 = soup.new_tag('i')
tag1.string = 'and Java'
tag.insert_after("on Python", tag1)
print (soup.prettify())

Output

<p>
   Excellent
   <b>
      Tutorials
   </b>
   from TutorialsPoint
</p>
on Python
<i>
   and Java
</i>
Advertisements