Change the tag’s contents and replace with the given string using BeautifulSoup
Last Updated :
26 May, 2021
Prerequisites: Beautifulsoup
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 change contents within a tag and replace the contents to be changed with the given string. For this, replace_with() function of the module is used.
Syntax:
replace_with(“string”)
Approach:
- Import module
- Scrap data from webpage
- Parse the string scraped to html
- Select tag within which replacement has to be performed
- Add string in place of the existing one using replace_with() function
- Print replaced content
Program:
Python3
from bs4 import BeautifulSoup
soup = BeautifulSoup(markup, 'html.parser' )
old_tag = soup.a
new_tag = soup.new_tag( "p" )
new_tag.string = "gfg.in"
old_tag.i.replace_with(new_tag)
print (old_tag)
|
Output:
<a href=”http://gfg.com/”>Geeks for Geeks <p>gfg.in</p></a>
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...