How to insert a new tag into a BeautifulSoup object?
Last Updated :
16 Mar, 2021
In this article, we will see how to insert a new tag into a BeautifulSoup object. See the below examples to get a better idea about the topic.
Example:
HTML_DOC :
“””
<html>
<head>
<title> Table Data </title>
</head>
<body>
<div> This is sample div 1 </div>
<div> This is sample div 2 </div>
</body>
</html>
“””
new_tag : <div> This is new div </div>
Modified BeautifulSoup Object :
“””
<html>
<head>
<title> Table Data </title>
</head>
<body>
<div> This is sample div 1 </div>
<div> This is sample div 2 </div>
<div> This is new div </div>
</body>
</html>
“””
Required Modules:
BeautifulSoup (bs4): It is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. Run the following command in the terminal to install this library-
pip install bs4
or
pip install beautifulsoup4
Creating a new tag using new_tag() method :
A new tag can be created by calling BeautifulSoup’s inbuilt function new_tag().
Inserting a new tag using the append() method :
The new tag is appended to the end of the parent tag.
Python3
from bs4 import BeautifulSoup
HTML_DOC =
def addTag(html):
soup = BeautifulSoup(html, "html.parser" )
new_div = soup.new_tag( "div" )
new_div.string = " This is new div "
soup.html.body.append(new_div)
print (soup)
addTag(HTML_DOC)
|
Output:
Inserting a new tag using insert() method :
Using this method, the new tag is not appended to the end of the parent tag but is inserted at a given numeric position. It works the same as the .insert() method of the Python list. For example, if we want to insert the new div between div 1 and div 2, we can use
soup.html.body.insert(2, new_div)
This would insert the new div at position 2 i.e, between the old 2 divs.
Python3
from bs4 import BeautifulSoup
HTML_DOC =
def addTag(html):
soup = BeautifulSoup(html, "html.parser" )
new_div = soup.new_tag( "div" )
new_div.string = " This is new div "
soup.html.body.insert( 2 , new_div)
print (soup)
addTag(HTML_DOC)
|
Output:
Inserting a new tag using insert_before() method :
insert_before() method is used to insert a new tag just before the given tag.
Python3
from bs4 import BeautifulSoup
HTML_DOC =
def addTag(html):
soup = BeautifulSoup(html, "html.parser" )
new_div_before = soup.new_tag( "div" )
new_div_before.string = " This is new div before div 1 "
soup.html.body.div.insert_before(new_div_before)
print (soup)
addTag(HTML_DOC)
|
Output:
Inserting a new tag using insert_after() method :
insert_after() method is used to insert a new tag just after the given tag.
Python3
from bs4 import BeautifulSoup
HTML_DOC =
def addTag(html):
soup = BeautifulSoup(html, "html.parser" )
new_div_after = soup.new_tag( "div" )
new_div_after.string = " This is new div after div 1 "
soup.html.body.div.insert_after(new_div_after)
print (soup)
addTag(HTML_DOC)
|
Output: