Open In App

Insert tags or strings immediately before and after specified tags using BeautifulSoup

BeautifulSoup is a Python library that is used for extracting data out of markup languages like HTML, XML…etc. For example let us say we have some web pages that needed to display relevant data related to some research like processing information such as date or address but that do not have any way to download it, in such cases BeautifulSoup comes handy to us as it helps us in pulling up particular content from HTML page and saves information. BeautifulSoup is an effective tool for web scraping that helps in cleaning and parsing documents that are pulled from the web.

Installation Of Required Libraries:

pip install bs4
pip install lxml 

Functions Used: 

Step-by-step Approach:

Implementation:

Example 1: Python Implementation for inserting tags or strings before Specified tags with BeautifulSoup.






# import module
from bs4 import BeautifulSoup
 
# assign URL
s = BeautifulSoup("<b>www.geeksforgeeks.com</b>",
                  "lxml")
 
print("Original Markup:")
print(s.b)
 
# insert tag
tag = s.new_tag("k")
tag.string = "Python"
 
print("\nNew Markup, before inserting the text:")
s.b.string.insert_before(tag)
print(s.b)

Output:



Example 2: Here is another Implementation for inserting tags or strings after Specified tags.




# import module
from bs4 import BeautifulSoup
 
# assign URL
s = BeautifulSoup("<b>www.geeksforgeeks.com</b>",
                  "lxml")
 
print("Original Markup:")
print(s.b)
 
# insert tag
tag = s.new_tag("k")
tag.string = "Python"
 
print("\nNew Markup, before inserting the text:")
s.b.string.insert_after(tag)
print(s.b)

Output:


Article Tags :