Saturday, November 16, 2024
Google search engine
HomeLanguagesBeautifulSoup – Wrap an element in a new tag

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




# 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:

Python3




# 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:

Python3




# 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:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments