Building Web Scrapers with Python and Beautiful Soup

Abstract workflow showing HTML product pages transformed into structured names and prices across multiple pages.

What You’ll Learn

In this lesson, you will build a Python scraper that requests an HTML page, parses it with Beautiful Soup, and extracts product names and prices. You will also practice using CSS selectors, handling missing elements, following pagination, and preparing scraped records for later use.

  • Understand the roles of requests and Beautiful Soup.
  • Select product elements from an HTML document.
  • Extract text and attribute values such as product names and prices.
  • Handle pagination and imperfect HTML safely.
Ad

The Concept

Web scraping is the process of retrieving a web page and extracting specific information from its HTML. A scraper usually has two main stages:

  1. Request the page: Python’s requests library downloads the HTML response.
  2. Parse the page: Beautiful Soup turns the HTML into a searchable tree of elements.

Beautiful Soup does not download pages by itself. It works with HTML that you provide, which is why requests and Beautiful Soup are commonly used together.

For example, a product might be represented by HTML like an article element containing a heading, a link, and a price. Instead of manually searching through a long string, you can use a CSS selector such as article.product_pod to find every product container, then search inside each container for its name and price.

Scraping is useful for tasks such as monitoring prices, collecting catalog data for analysis, or importing publicly available information into another application. Always check a site’s terms of use and robots.txt, avoid sending excessive requests, and do not scrape private or restricted data.

If the libraries are not installed in your environment, install them with:

python -m pip install requests beautifulsoup4

Basic Example

The Books to Scrape site is designed for practicing scraping. The following example downloads its home page and prints the first three product names and prices.

import requests
from bs4 import BeautifulSoup

url = "https://books.toscrape.com/"
response = requests.get(url, timeout=10)
response.raise_for_status()

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

for product in soup.select("article.product_pod")[:3]:
    name = product.select_one("h3 a")["title"]
    price = product.select_one(".price_color").get_text(strip=True)
    print(f"{name}: {price}")

Expected Output

The site may change over time, but the first products currently produce output similar to this:

A Light in the Attic: £51.77
Tipping the Velvet: £53.74
Soumission: £50.10

How the Code Works

A process diagram showing a scraper starting with a page URL, requesting and validating the HTML response, parsing it with Beautiful Soup, selecting product cards, checking for missing name or price fields, building structured product records, and following pagination until no next page remains.
The scraper requests and parses each page, safely extracts product records, skips incomplete cards, and follows next-page links until collection is complete.

The call to requests.get downloads the page. The timeout prevents the program from waiting indefinitely if the server does not respond. Calling raise_for_status raises an exception for an unsuccessful HTTP response, such as a 404 or 500 response, instead of allowing the scraper to continue with an error page.

Beautiful Soup parses the response text with the HTML parser. The selector article.product_pod matches each product card on this particular site. The selector is based on the page’s HTML structure, so selectors are one of the parts of a scraper most likely to need updating when a site redesigns its page.

Inside each product card, h3 a finds the product link. The product name is stored in the link’s title attribute, so square brackets retrieve that attribute. The .price_color selector finds the price element, and get_text with strip enabled removes surrounding whitespace.

The scraper deliberately selects only the first three products for readable output. Removing the slice would process every product on the page.

Another Example

A useful scraper usually returns structured records rather than printing values immediately. The next example defines a function that extracts all products from a page and follows the site’s next-page link. It also converts each displayed price into a numeric value so the records can be filtered or analyzed.

from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup


def scrape_product_page(url):
    response = requests.get(url, timeout=10)
    response.raise_for_status()

    soup = BeautifulSoup(response.text, "html.parser")
    products = []

    for card in soup.select("article.product_pod"):
        name_link = card.select_one("h3 a")
        price_element = card.select_one(".price_color")

        if name_link is None or price_element is None:
            continue

        price_text = price_element.get_text(strip=True)
        price_value = float(price_text.replace("£", ""))

        products.append({
            "name": name_link.get("title", name_link.get_text(strip=True)),
            "price": price_value,
            "currency": "GBP"
        })

    next_link = soup.select_one("li.next a")
    next_url = urljoin(url, next_link["href"]) if next_link else None

    return products, next_url


all_products = []
page_url = "https://books.toscrape.com/"

for page_number in range(2):
    page_products, next_page = scrape_product_page(page_url)
    all_products.extend(page_products)

    if next_page is None:
        break

    page_url = next_page

affordable_products = [
    product for product in all_products
    if product["price"] < 20
]

print(f"Scraped {len(all_products)} products.")
print(f"Products under £20: {len(affordable_products)}")
print(affordable_products[0])

The returned dictionaries make the data easier to reuse. For example, you could serialize scraped data with JSON after collecting it, send it to another part of an application, or load it into a data-analysis tool.

Common Mistakes

Using a selector that matches nothing

Selectors depend on the actual HTML. If a selector is wrong, methods such as select return an empty list, while select_one returns None. Inspect the page source or browser developer tools to confirm element names and classes. Also remember that a class selector begins with a period, while an element selector does not.

Assuming every element exists

A product might lack a price, title, image, or link because of malformed HTML or a special product type. Calling an attribute or method on None causes an exception. The second example checks both the name link and price element before extracting them.

Ignoring HTTP failures

A request can fail because of a server error, a missing page, or a connection problem. Use a timeout and call raise_for_status so failures are visible. For a larger scraper, you could catch requests exceptions, record the failed URL, and continue with other pages.

Assuming visible HTML contains every piece of data

Some websites create product listings with JavaScript after the initial page loads. Requests receives the initial HTML but does not execute JavaScript. If the needed products are absent from response.text, inspect whether the site provides an accessible API or server-rendered page. Do not assume Beautiful Soup can extract content that was never included in the downloaded HTML.

Try It Yourself

Modify the basic scraper so that it:

  • Processes every product on the first page instead of only three.
  • Prints only products whose price is below £30.
  • Prints the number of matching products after the loop.

Use the existing product selectors and convert the price text to a number before comparing it. This exercise reinforces selecting elements, looping through results, and using dictionaries or variables to organize extracted data.

Challenge

Build a scraper for the first three pages of Books to Scrape with these requirements:

  • Collect each product’s name and numeric price.
  • Skip a product if its name or price element is missing.
  • Calculate the average price of all collected products.
  • Print the five cheapest products in ascending price order.
  • Print the total number of products and the average price.

Use a function for scraping one page and follow the next-page link rather than hard-coding three separate URLs.

Solution

from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup


def scrape_page(url):
    response = requests.get(url, timeout=10)
    response.raise_for_status()

    soup = BeautifulSoup(response.text, "html.parser")
    products = []

    for card in soup.select("article.product_pod"):
        name_link = card.select_one("h3 a")
        price_element = card.select_one(".price_color")

        if name_link is None or price_element is None:
            continue

        price_text = price_element.get_text(strip=True)
        price = float(price_text.replace("£", ""))

        products.append({
            "name": name_link.get("title", name_link.get_text(strip=True)),
            "price": price
        })

    next_link = soup.select_one("li.next a")
    next_url = urljoin(url, next_link["href"]) if next_link else None

    return products, next_url


products = []
page_url = "https://books.toscrape.com/"

for _ in range(3):
    page_products, next_page = scrape_page(page_url)
    products.extend(page_products)

    if next_page is None:
        break

    page_url = next_page

if products:
    average_price = sum(product["price"] for product in products) / len(products)
    cheapest_products = sorted(products, key=lambda product: product["price"])[:5]

    print(f"Products scraped: {len(products)}")
    print(f"Average price: £{average_price:.2f}")
    print("Five cheapest products:")

    for product in cheapest_products:
        print(f"- {product['name']}: £{product['price']:.2f}")
else:
    print("No products were found.")

The solution keeps page retrieval and parsing inside a reusable function. It uses the next link returned by each page, protects against missing product fields, and stores each result as a dictionary. Sorting creates a new list ordered by price, while the slice keeps only the five cheapest products. The empty-list check prevents division by zero if the site returns no products.

Key Takeaways

  • Requests downloads HTML, while Beautiful Soup parses and searches that HTML.
  • CSS selectors such as article.product_pod and .price_color identify the data to extract.
  • Check for missing elements and HTTP errors before processing scraped data.
  • Return product records as dictionaries when the data will be filtered, sorted, saved, or analyzed later.
  • Scrapers depend on a site’s HTML structure and should be written with respectful request rates and maintainability in mind.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad