Beautiful Soup - insert_before() Method



Method Description

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

Syntax

insert_before(*args)

Parameters

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

Return Value

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

Example 1

The following example inserts a text "Here is an" before "Excellent in the given HTML markup string.

from bs4 import BeautifulSoup, NavigableString

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

tag.insert_before("Here is an ")
print (soup.prettify())

Output

Here is an
<b>
   Excellent
</b>
   Python Tutorial
<u>
   from TutorialsPoint
</u>

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</u>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b
tag1 = soup.new_tag('b')
tag1.string = "Python "
tag.insert_before(tag1)
print (soup.prettify())

Output

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

Example 3

The following code passes more than one strings to be inserted before the <b> tag.

from bs4 import BeautifulSoup

markup = '<p>There are <b>Tutorials</b> <u>from TutorialsPoint</u></p>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b

tag.insert_before("many ", 'excellent ')
print (soup.prettify())

Output

<p>
   There are
   many
   excellent
   <b>
      Tutorials
   </b>
   <u>
      from TutorialsPoint
   </u>
</p>
Advertisements