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:
- Import module.
- Scrap data from a webpage.
- Parse the string scraped to HTML.
- Use wrap() function to wrap the element.
- Print the result.
Below are some implementations of the above approach:
Example 1:
Python3
from bs4 import BeautifulSoup
markup = '
<p>Geeks for Geeks< / p>
'
soup = BeautifulSoup(markup, 'html.parser' )
print (soup)
soup.p.string.wrap(soup.new_tag( "i" ))
print (soup)
soup.p.wrap(soup.new_tag( "div" ))
print (soup)
|
Output:
Example 2:
Python3
from bs4 import BeautifulSoup
markup = '
<p>Hello World< / p>
'
soup = BeautifulSoup(markup, 'html.parser' )
print (soup)
soup.p.string.wrap(soup.new_tag( "u" ))
print (soup)
|
Output:
Example 3:
Python3
from bs4 import BeautifulSoup
markup = '
<p>Python 3 < / p>
'
soup = BeautifulSoup(markup, 'html.parser' )
print (soup)
soup.p.wrap(soup.new_tag( "h2" ))
print (soup)
|
Output:
Last Updated :
30 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...