How to Build a Python Web Scraper for Public Webpages: A Beginner’s Practical Project
Learn how to extract information from public webpages using Python, BeautifulSoup and Pandas, and save the collected data into a CSV file.
Introduction
Have you ever wondered how websites collect and organise information from different webpages?
Imagine collecting product names, book titles, prices or article headlines from a webpage. Instead of copying each piece of information manually, you can use a Python program to automate the process.
This technique is called web scraping.
Web scraping is a useful practical skill for Python beginners who want to understand automation, data collection and data analysis. In this tutorial, we will build a simple Python web scraper that extracts book titles and prices from a public practice website and saves the information into a CSV file.
By the end of this project, you will understand how web scraping works and how to build a basic data extraction program using Python.
1. What Is Web Scraping in Python?
Web scraping is the process of collecting information from webpages automatically using a computer program.
Python makes web scraping easier because it provides libraries that help developers:
- Send requests to webpages.
- Read HTML content.
- Find specific elements on a webpage.
- Extract text and links.
- Store collected information in files.
For example, a Python web scraper can help collect:
- Product names and prices.
- Book titles and ratings.
- Public article headlines.
- Publicly available job listings.
- Educational information.
Web scraping should always respect a website's terms of service, robots.txt instructions, copyright and privacy requirements. Only collect information you are permitted to access, and avoid private, personal or restricted data.
2. How Does Python Web Scraping Work?
A basic web scraping project follows five steps:
- Send a request: Python connects to a permitted webpage.
- Receive HTML: The website returns its webpage content.
- Parse HTML: BeautifulSoup helps understand the page structure.
- Extract information: Python selects the required elements.
- Save the data: Pandas stores the extracted information in a CSV file.
In simple terms:
Webpage → Python Request → HTML Parsing → Data Extraction → CSV File
3. Python Libraries Required for Web Scraping
We will use three Python libraries in this project.
A. Requests
The Requests library sends HTTP requests to webpages and retrieves their responses.
B. BeautifulSoup
BeautifulSoup is used to parse HTML and extract information from specific HTML elements.
C. Pandas
Pandas helps organise extracted information into a table and export it into formats such as CSV.
4. Set Up Your Python Environment
Before writing the code, make sure Python is installed on your computer.
You can use:
- Python IDLE
- Visual Studio Code
- PyCharm
- Jupyter Notebook
Open your terminal or command prompt and install the required libraries:
pip install requests beautifulsoup4 pandas
Once installation is complete, you are ready to build your first scraper.
5. Choose a Website for the Project
For this beginner project, we will use Books to Scrape, a practice website designed for learning web scraping.
Website: https://books.toscrape.com/
It provides sample book listings that beginners can use to practise extracting publicly displayed information.
We will collect two details:
- Book title
- Book price
6. Write Your First Python Web Scraper
Create a new Python file named:
web_scraper.py
Now add the following code:
import requests
from bs4 import BeautifulSoup
import pandas as pd
# Website URL
url = "https://books.toscrape.com/"
# Send request to website
response = requests.get(
url,
timeout=15,
headers={"User-Agent": "EducationalPythonScraper/1.0"}
)
# Check response status
response.raise_for_status()
# Parse HTML content
soup = BeautifulSoup(response.text, "html.parser")
# Find all book containers
books = soup.select("article.product_pod")
# Create an empty list
book_data = []
# Extract book details
for book in books:
title = book.h3.a["title"]
price = book.select_one(".price_color").get_text(
strip=True
)
book_data.append({
"Book Title": title,
"Price": price
})
# Convert data into a DataFrame
df = pd.DataFrame(book_data)
# Save data into CSV file
df.to_csv("books_data.csv", index=False)
print(df)
print("Web scraping completed successfully!")
7. Understand the Python Code Step by Step
Let's understand what each section of the program does.
Step 1: Import Libraries
import requests
from bs4 import BeautifulSoup
import pandas as pd
These statements import the libraries required for sending requests, parsing HTML and organising data.
Step 2: Send a Request
response = requests.get(url, timeout=15)
This sends an HTTP GET request to the selected webpage.
The server returns a response containing the webpage content if the request is allowed.
Step 3: Parse the HTML
soup = BeautifulSoup(response.text, "html.parser")
This converts the HTML response into a structure that Python can search and navigate.
Step 4: Find Book Information
books = soup.select("article.product_pod")
This selects the HTML elements representing individual book listings.
We then extract each book's title and price:
title = book.h3.a["title"]
price = book.select_one(".price_color").get_text(
strip=True
)
Step 5: Store the Extracted Data
book_data.append({
"Book