DEV Community

Cover image for How to Build Your First Web Scraper in Python (Beginner Tutorial)
Sameer Qaiser
Sameer Qaiser

Posted on

How to Build Your First Web Scraper in Python (Beginner Tutorial)

Have you ever wanted to pull data from a website, but there was no "Export to CSV" button?

Maybe you wanted to track prices on an e-commerce site, gather quotes for a project, or analyze data from a directory.

The good news? You don’t need expensive software to do this. You can build a custom web scraper in Python in just a few minutes.

In this beginner-friendly guide, we are going to build a simple web scraper using Python. We'll scrape a dummy e-commerce site (built specifically for practicing scraping) and save the data to a CSV file.

Let’s dive in. 🐍

🛠️ Prerequisites

Before we start, make sure you have Python installed on your machine. You will also need to install two external libraries. Open your terminal or command prompt and run:

pip install requests beautifulsoup4
Enter fullscreen mode Exit fullscreen mode
  • requests: Allows Python to send HTTP requests to a website.
  • beautifulsoup4: Parses the HTML of the website so we can extract specific data.

Step 1: Fetching the Webpage

First, we need to tell Python to go to the website and download the HTML.

We are going to use Books to Scrape, a safe sandbox site created specifically for testing web scrapers.

Create a new file named scraper.py and add this code:

import requests
from bs4 import BeautifulSoup

url = "http://books.toscrape.com/"

response = requests.get(url)

if response.status_code == 200:
    print("Successfully fetched the webpage!")
else:
    print(f"Failed to fetch. Status code: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

Run this script. If you see "Successfully fetched the webpage!", you are ready for the next step.


Step 2: Parsing the HTML

Now that we have the raw HTML, we need to use BeautifulSoup to make it readable and searchable by Python.

Add this to your script:

soup = BeautifulSoup(response.content, "html.parser")

print(soup.title.text)
Enter fullscreen mode Exit fullscreen mode

Step 3: Finding the Data

To extract specific data, we need to inspect the website's HTML structure.
If you go to Books to Scrape and right-click on a book title, you'll see it is wrapped in an <h3> tag, and the actual title is inside an <a> tag.

Let's find all the books on the page and extract their titles and prices:

books = soup.find_all("article", class_="product_pod")

for book in books:

    title = book.h3.a["title"]

    price = book.find("p", class_="price_color").text

    print(f"Title: {title} | Price: {price}")
Enter fullscreen mode Exit fullscreen mode

If you run this, you should see a list of books and their prices printed in your terminal!


Step 4: Saving The Data to a CSV

Printing to the terminal is cool, but real automation means saving the data so you can use it in Excel or Google Sheets.

We will use Python's built-in csv module to save our data.

Here is the complete, final code:

import requests
from bs4 import BeautifulSoup
import csv

url = "http://books.toscrape.com/"
response = requests.get(url)

if response.status_code == 200:
    soup = BeautifulSoup(response.content, "html.parser")
    books = soup.find_all("article", class_="product_pod")


    with open("books_data.csv", mode="w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
         Write the header row
        writer.writerow(["Title", "Price"])


        for book in books:
            title = book.h3.a["title"]
            price = book.find("p", class_="price_color").text

            writer.writerow([title, price])

    print("Scraping complete! Data saved to books_data.csv")
else:
    print("Failed to fetch the webpage.")
Enter fullscreen mode Exit fullscreen mode

Run your script one last time. You will now see a books_data.csv file in your project folder containing all the books and their prices.


⚠️ A Quick Note on Scraping Ethics

Before you go out and scrape your favorite websites, remember:

  • Always check the website's robots.txt file (e.g., website.com/robots.txt) to see if they allow scraping.
  • Don't hammer servers with thousands of requests per second. Add time.sleep(1) between requests to be polite.
  • Never scrape personal or protected data.

Wrapping Up

And just like that, you wrote your first web scraper! This is the foundation of data engineering and automation. You can now tweak this code to extract reviews, images, or any other data you need.

Top comments (0)