Prerequisites: Beautifulsoup
Beautifulsoup is a Python library used to extract the contents from the webpages. It is used in extracting the contents from HTML and XML structures. To use this library, we need to install it first. Here we are going to append the text to the existing contents of tag. We will do this with the help of the BeautifulSoup library.
Approach
- Import module
- Open HTML file
- Read contents
- Append content to the required tag
- Save changes to the file
Function used:
Append function of the Beautifulsoup module is used to append content to desired tags.
Syntax:
append(“<string>”
File Used:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Append </ title > </ head > < body > < h1 >Append to the </ h1 > < p >We are going to append to the contents using </ p > </ body > </ html > |
Python Code:
Python3
# Python program to append to the contents of tag # Importing library from bs4 import BeautifulSoup # Opening and reading the html file file = open ( "gfg.html" , "r" ) contents = file .read() soup = BeautifulSoup(contents, "lxml" ) # Appending to the contents of 'title' tag in html file print ( "Current content in title tag is:-" ) print (soup.title) soup.title.append( "Using BS" ) print ( "Content after appending is:-" ) print (soup.title) print ( "\n" ) # Appending to the contents of 'h1' tag in html file print ( "Current content in heading h1 tag is:-" ) print (soup.h1) soup.h1.append( "contents of tag" ) print ( "Content after appending is:-" ) print (soup.h1) print ( "\n" ) # Appending to the contents of 'p' tag in html file print ( "Current content in paragraph p tag is:-" ) print (soup.p) soup.p.append( "BeautifulSoup library" ) print ( "Content after appending is:-" ) print (soup.p) print ( "\n" ) # Appending to the contents of 'a' tag in html file print ( "Current content in anchor a tag is:-" ) print (soup.a) soup.a.append( "Geeks Website" ) print ( "Content after appending is:-" ) print (soup.a) # Code to save the changes in 'output.html' file savechanges = soup.prettify( "utf-8" ) with open ( "output.html" , "wb" ) as file : file .write(savechanges) |
Output: