How to modify HTML using BeautifulSoup ?
Last Updated : 10 Sep, 2024
BeautifulSoup in Python helps in scraping the information from web pages made of HTML or XML. Not only it involves scraping data but also involves searching, modifying, and iterating the parse tree. In this article, we will discuss modifying the content directly on the HTML web page using BeautifulSoup.
Syntax:
old_text = soup.find("#Widget", {"id":"#Id name of widget in which you want to edit"})
old_text.string = re.sub(r'Text you want to edit', 'New Text', old_text.string)
Terms Used:
- Widget: Here, widget stands for the particular widget in which the text you wish to replace from the website is currently stored.
- Id Name: Here, Id Name stands for the name you have given to the Id of the particular widget in which text is stored.
- old_text.string accesses the text content inside an HTML element (or tag) represented by old_text, allowing you to directly read or modify that text if the element contains only a single text node.
Note: when multiple text node is present one should use .contents, .strings, .children etc. with loops.
Example:
For instance, consider this simple page source.
HTML <!DOCTYPE html> <html> <head> My First Heading </head> <body> <p id="para"> Geeks For Geeks </p> </body> </html>
Once you have created a driver, you can replace the text 'Geeks For Geeks' with 'Vinayak Rai' using –
old_text = soup.find("p", {"id": "para"})
old_text.string = re.sub(r'Geeks For Geeks', 'Vinayak Rai', old_text.string)
Step-by-step Approach:
Step 1: First, import the libraries Beautiful Soup, os and re.
from bs4 import BeautifulSoup as bs
import os
import re
Step 2: Now, remove the last segment of the path.
base=os.path.dirname(os.path.abspath(__file__))
Step 3: Open and Parse the HTML File
with open(os.path.join(base, '#HTML filename you want to edit)) as html_file:
soup = bs(html_file, 'html.parser')
Step 4: Further, give the appropriate location of the text which you wish to replace.
old_text=soup.find("#Widget Name", {"id":"#Id name of widget in which you want to edit"})
Step 5: Next, replace the already stored text with the new text you wish to assign.
old_text.string=re.sub(r'#Text which you want to edit', '#New Text which you want to replace with', old_text.string)
Step 7: Finally, alter the HTML file to see the changes done in the previous step.
with open("#HTML filename in which you want to store the edited text", "wb") as f_output:
f_output.write(soup.prettify("utf-8"))
Implementation:
Python # Python program to modify HTML # with the help of Beautiful Soup # Import the libraries from bs4 import BeautifulSoup as bs import os import re # Remove the last segment of the path base = os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to make changes with open(os.path.join(base, 'gfg.html')) as html_file: # Parse HTML file in Beautiful Soup soup = bs(html_file, 'html.parser') # Give location where text is stored which you wish to alter old_text = soup.find("p", {"id": "para"}) # Replace the already stored text with the new text which you wish to assign old_text.string = re.sub(r'Geeks For Geeks', 'Vinayak Rai', old_text.string) # Alter HTML file to see the changes done with open("gfg.html", "wb") as f_output: f_output.write(soup.prettify("utf-8"))
Output:
how-to-modify-html-using-beautifulsoup
Similar Reads
BeautifulSoup - Scraping List from HTML
Prerequisite:Â RequestsBeautifulSoup Python can be employed to scrap information from a web page. It can also be used to retrieve data provided within a specific tag, this article how list elements can be scraped from HTML. Module Needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data
2 min read
How to Remove tags using BeautifulSoup in Python?
Prerequisite- Beautifulsoup module In this article, we are going to draft a python script that removes a tag from the tree and then completely destroys it and its contents. For this, decompose() method is used which comes built into the module. Syntax: Beautifulsoup.Tag.decompose() Tag.decompose() r
2 min read
BeautifulSoup - Scraping Link from HTML
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup In this article, we will understand how we can extract all the links from a URL or an HTML document using Python. Libraries Required:bs4 (BeautifulSoup): It is a library in python which makes it easy to scrape information from web
2 min read
How to Use lxml with BeautifulSoup in Python
In this article, we will explore how to use lxml with BeautifulSoup in Python. lxml is a high-performance XML and HTML parsing library for Python, known for its speed and comprehensive feature set. It supports XPath, XSLT, validation, and efficient handling of large documents, making it a preferred
3 min read
How to Scrape Nested Tags using BeautifulSoup?
We can scrap the Nested tag in beautiful soup with help of. (dot) operator. After creating a soup of the page if we want to navigate nested tag then with the help of. we can do it. For scraping Nested Tag using Beautifulsoup follow the below-mentioned steps. Step-by-step Approach Step 1: The first s
3 min read
How to Search the Parse Tree using BeautifulSoup?
Searching the parse tree means we need to find the tag and the content of the HTML tree. This can be done in many ways. But the most used method for searching the parse tree is the find() and find_all() method. With the help of this, we can parse the HTML tree using Beautifulsoup. For Searching the
2 min read
Extract JSON from HTML using BeautifulSoup in Python
In this article, we are going to extract JSON from HTML using BeautifulSoup in Python. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.pip inst
3 min read
Retrieve children of the html tag using BeautifulSoup
Prerequisites: Beautifulsoup Beautifulsoup is a Python module that is used for web scraping. This article discusses how children tags of given HTML tags can be scraped and displayed. Sample Website:https://www.geeksforgeeks.org/caching-page-tables/ For First Child: Approach Import modulePass the URL
3 min read
How to Import BeautifulSoup in Python
Beautiful Soup is a Python library used for parsing HTML and XML documents. It provides a simple way to navigate, search, and modify the parse tree, making it valuable for web scraping tasks. In this article, we will explore how to import BeautifulSoup in Python. What is BeautifulSoup?BeautifulSoup
3 min read
Show text inside the tags using BeautifulSoup
Prerequisite: RequestsBeautifulSoup In this article, we will learn how to get a text from HTML tags using BeautifulSoup. Here we will use requests & BeautifulSoup Module in Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST
2 min read