Open In App

BeautifulSoup – Wrap an element in a new tag

Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify HTML webpages. This article depicts how beautifulsoup can be employed to wrap an element in a new tag. 

To perform this task, the wrap() method of the module is used. The wrap() method wraps an entity or places the stated tag before and after the entity. It returns a new wrapper.



Approach:

Below are some implementations of the above approach:



Example 1:




# importing BeautifulSoup Module
from bs4 import BeautifulSoup
 
markup = '
 
<p>Geeks for Geeks</p>
 
'
 
# parsering string to HTML
soup = BeautifulSoup(markup, 'html.parser')
print(soup)
 
# wrapping around the string
soup.p.string.wrap(soup.new_tag("i"))
print(soup)
 
# wrapping around the tag
soup.p.wrap(soup.new_tag("div"))
print(soup)

Output:

Example 2:




# importing BeautifulSoup Module
from bs4 import BeautifulSoup
 
markup = '
 
<p>Hello World</p>
 
'
 
# parsering string to HTML
soup = BeautifulSoup(markup, 'html.parser')
print(soup)
 
# wrapping around the string
soup.p.string.wrap(soup.new_tag("u"))
print(soup)

Output:

Example 3:




# importing BeautifulSoup Module
from bs4 import BeautifulSoup
 
markup = '
 
<p>Python 3 </p>
 
'
 
# parsering string to HTML
soup = BeautifulSoup(markup, 'html.parser')
print(soup)
 
# wrapping around the tag
soup.p.wrap(soup.new_tag("h2"))
print(soup)

Output:


Article Tags :