![]() |
VOOZH | about |
BeautifulSoup is a Python library used for web scraping. It helps parse HTML and XML documents making it easy to navigate and extract specific parts of a webpage. This article explains the steps of web scraping using BeautifulSoup.
Now, let’s go through the web scraping process step by step.
Before starting with the steps, make sure to install all the necessary libraries. Run the following commands on command prompt or terminal using pip:
pip install requests
pip install beautifulsoup4
The first step in web scraping is to send an HTTP request to the target webpage and fetch its raw HTML content. This is done using requests library.
Explanation:
Note: If you're facing issues like "403 Forbidden" try adding a browser user agent like below. You can find your user agent online based on device and browser.
Now that we have raw HTML, the next step is to parse it using BeautifulSoup so we can easily navigate and extract specific parts of the content.
Explanation:
Note: BeautifulSoup supports different parsers like html.parser, lxml and html5lib. Choose one by specifying it as the second argument.
For Example: soup = BeautifulSoup(response.text, 'html5lib')
Now that the HTML is parsed, specific elements like text, links or images can be extracted by targeting tags and classes using BeautifulSoup methods like .find() or .find_all().
Suppose we want to extract quotes from a website then we will do:
Explanation:
Before extracting data, it’s helpful to inspect the HTML structure using soup.prettify() to find out where the information is written in the code of the page.
For example: quotes is inside a <div> with a specific id or class, we can find it using:
container = soup.find('div', attrs={'id': 'all_quotes'})
find() gets the first <div> that has id="all_quotes".
If there are multiple quote boxes inside that section, we can use:
container.find_all()
Now that the data is extracted, it can be saved into a CSV file for easy storage and future use. Python’s built-in csv module is used to write the data in a structured format.
Explanation:
This script scrapes inspirational quotes from the website, parses the HTML content, extracts relevant information and saves the data to a quotes.csv file for later use.