ZetCode

Python web scraping with BeautifulSoup

last modified November 29, 2026 Python 3.15

In this article we scrape a complete website with Python and the BeautifulSoup library. Step by step, we build a scraper that collects books from an online bookstore.

Web scraping is fetching web pages and extracting data from them with a program. BeautifulSoup turns an HTML document into a tree of Python objects that we search with tag names and CSS selectors. The library itself is covered in BeautifulSoup, and the general techniques, such as setting the User-Agent, handling errors, and robots.txt, in web scraping. Here we apply them to one site.

The target is books.toscrape.com, a sandbox bookstore built for practising web scraping. It has 1000 books in 50 categories, spread over 50 catalogue pages, each book with its own detail page. We fetch the pages with Requests and use the lxml parser.

$ pip install requests beautifulsoup4 lxml

Looking at the store

We start by downloading the home page and checking what it contains.

store_page.py
import requests
from bs4 import BeautifulSoup

url = 'https://books.toscrape.com/'
resp = requests.get(url, timeout=10)
soup = BeautifulSoup(resp.text, 'lxml')

print(soup.title.get_text(strip=True))
print(len(soup.select('article.product_pod')), 'books on the page')
print(soup.select_one('li.current').get_text(strip=True))

The program prints the title of the page, the number of books on it, and the position in the catalogue.

soup = BeautifulSoup(resp.text, 'lxml')

The lxml parser is faster than the built-in html.parser.

print(soup.title.get_text(strip=True))

The title in the source is surrounded by newlines and spaces; the strip=True argument removes them.

print(len(soup.select('article.product_pod')), 'books on the page')
print(soup.select_one('li.current').get_text(strip=True))

Looking at the page source in a browser tells us that every book is an article element with the product_pod class and that the pager has a li with the current class. Finding such classes is the first step of every scraping job.

$ python store_page.py
All products | Books to Scrape - Sandbox
20 books on the page
Page 1 of 50

Fixing the encoding

Prices on the site are in pounds. When we print one, we get a surprise.

price_encoding.py
import requests
from bs4 import BeautifulSoup

url = 'https://books.toscrape.com/'
resp = requests.get(url, timeout=10)

print(resp.headers['Content-Type'])
print(resp.encoding)

soup = BeautifulSoup(resp.text, 'lxml')
print(soup.select_one('p.price_color').get_text())

resp.encoding = 'utf-8'

soup = BeautifulSoup(resp.text, 'lxml')
print(soup.select_one('p.price_color').get_text())

The program prints the first price twice, before and after setting the encoding.

print(resp.headers['Content-Type'])
print(resp.encoding)

The server sends text/html without a charset. In that case, Requests follows the old HTTP default and decodes the body as ISO-8859-1. The page is in UTF-8, so the two-byte pound sign turns into £.

resp.encoding = 'utf-8'

Setting the encoding before reading resp.text fixes the problem. Another way is to pass the raw bytes in resp.content to BeautifulSoup, which then reads the charset from the meta tag of the document.

$ python price_encoding.py
text/html
ISO-8859-1
£51.77
£51.77

Extracting book cards

Each book card contains a link with the title, the price, and a star rating. We print the parts of the first five cards.

book_cards.py
import requests
from bs4 import BeautifulSoup

url = 'https://books.toscrape.com/'
resp = requests.get(url, timeout=10)
resp.encoding = 'utf-8'
soup = BeautifulSoup(resp.text, 'lxml')

for card in soup.select('article.product_pod', limit=5):

    link = card.select_one('h3 a')
    price = card.select_one('p.price_color').get_text()
    rating = card.select_one('p.star-rating')['class']

    print(link.get_text())
    print('   ', link['title'])
    print('   ', price, rating, link['href'])

The output shows that the visible data is not always the data we want.

for card in soup.select('article.product_pod', limit=5):

The limit argument stops the search after five matches.

print(link.get_text())
print('   ', link['title'])

The text of the link is shortened with an ellipsis for long titles. The full title is in the title attribute.

rating = card.select_one('p.star-rating')['class']

The rating is not text at all: it is the second class of the p element, which the stylesheet turns into stars. BeautifulSoup returns the class attribute as a list, because an element can have several classes. The href of the link is relative to the current page.

$ python book_cards.py
A Light in the ...
    A Light in the Attic
    £51.77 ['star-rating', 'Three'] catalogue/a-light-in-the-attic_1000/index.html
Tipping the Velvet
    Tipping the Velvet
    £53.74 ['star-rating', 'One'] catalogue/tipping-the-velvet_999/index.html
Soumission
    Soumission
    £50.10 ['star-rating', 'One'] catalogue/soumission_998/index.html
Sharp Objects
    Sharp Objects
    £47.82 ['star-rating', 'Four'] catalogue/sharp-objects_997/index.html
Sapiens: A Brief History ...
    Sapiens: A Brief History of Humankind
    £54.23 ['star-rating', 'Five'] catalogue/sapiens-a-brief-history-of-humankind_996/index.html

Converting values

Scraped data is text. To compute with it, we convert prices to numbers and rating words to integers.

book_values.py
from decimal import Decimal

import requests
from bs4 import BeautifulSoup

RATINGS = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5}

url = 'https://books.toscrape.com/'
resp = requests.get(url, timeout=10)
resp.encoding = 'utf-8'
soup = BeautifulSoup(resp.text, 'lxml')

books = []

for card in soup.select('article.product_pod'):

    price = card.select_one('p.price_color').get_text()
    rating = card.select_one('p.star-rating')['class'][1]

    books.append({
        'title': card.select_one('h3 a')['title'],
        'price': Decimal(price.removeprefix('£')),
        'rating': RATINGS[rating],
    })

cheapest = min(books, key=lambda b: b['price'])
total = sum(b['price'] for b in books)

print('cheapest:', cheapest['title'], cheapest['price'])
print('average price:', round(total / len(books), 2))
print('five stars:', [b['title'] for b in books if b['rating'] == 5])

The program finds the cheapest book on the first page, the average price, and the books with five stars.

RATINGS = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5}

A dictionary maps the class names to numbers.

'price': Decimal(price.removeprefix('£')),

We remove the currency sign and create a Decimal, which represents money exactly; a float would introduce rounding errors.

cheapest = min(books, key=lambda b: b['price'])
total = sum(b['price'] for b in books)

Once the data is in dictionaries, ordinary Python does the rest.

$ python book_values.py
cheapest: Starving Hearts (Triangular Trade Trilogy, #1) 13.99
average price: 38.05
five stars: ['Sapiens: A Brief History of Humankind', 'Set Me Free', "Scott Pilgrim's Precious Little Life (Scott Pilgrim #1)", 'Rip it Up and Start Again']

Following a link to a detail page

The catalogue shows only a summary of each book. The UPC code, the number of copies in stock, and the description are on the detail page.

book_detail.py
import re
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup

url = 'https://books.toscrape.com/'
resp = requests.get(url, timeout=10)
soup = BeautifulSoup(resp.content, 'lxml')

href = soup.select_one('article.product_pod h3 a')['href']
url = urljoin(url, href)
print(url)

resp = requests.get(url, timeout=10)
soup = BeautifulSoup(resp.content, 'lxml')

info = {}
for row in soup.select('table.table-striped tr'):
    info[row.th.get_text()] = row.td.get_text()

print(soup.h1.get_text())
print('category:', soup.select('ul.breadcrumb a')[-1].get_text())
print('UPC:', info['UPC'])

stock = re.search(r'\d+', info['Availability']).group()
print('in stock:', int(stock))

desc = soup.select_one('#product_description + p').get_text()
print(desc[:60] + '...')

The program follows the link of the first book and reads its detail page.

soup = BeautifulSoup(resp.content, 'lxml')

This time we pass the bytes, so we do not have to set the encoding.

url = urljoin(url, href)

The urljoin function resolves the relative link against the URL of the page where we found it.

info = {}
for row in soup.select('table.table-striped tr'):
    info[row.th.get_text()] = row.td.get_text()

The product information is a table with a header cell and a data cell in each row. We turn it into a dictionary.

print('category:', soup.select('ul.breadcrumb a')[-1].get_text())

The breadcrumb navigation ends with the category of the book.

stock = re.search(r'\d+', info['Availability']).group()

The availability is a sentence such as In stock (22 available); a regular expression extracts the number.

desc = soup.select_one('#product_description + p').get_text()

The description paragraph has no class of its own. It follows the div with the product_description id, so we use the + combinator, which selects the next sibling.

$ python book_detail.py
https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html
A Light in the Attic
category: Poetry
UPC: a897fe39b1053632
in stock: 22
It's hard to imagine a world without A Light in the Attic. T...

A helper module

The next programs download many pages, so we move the established code into a module. It sends all requests through one session, waits half a second after each request, and parses book cards and pager links.

bookstore.py
import time
from decimal import Decimal
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup

BASE = 'https://books.toscrape.com/'
RATINGS = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5}

session = requests.Session()
session.headers['User-Agent'] = 'book-collector/1.0'


def fetch(url):

    resp = session.get(url, timeout=10)
    resp.raise_for_status()
    time.sleep(0.5)

    return BeautifulSoup(resp.content, 'lxml')


def parse_card(card, page_url):

    link = card.select_one('h3 a')
    price = card.select_one('p.price_color').get_text()
    rating = card.select_one('p.star-rating')['class'][1]

    return {
        'title': link['title'],
        'price': Decimal(price.removeprefix('£')),
        'rating': RATINGS[rating],
        'url': urljoin(page_url, link['href']),
    }


def next_page(soup, page_url):

    link = soup.select_one('li.next a')
    return urljoin(page_url, link['href']) if link else None

The module contains no new techniques; it collects what the previous sections have shown.

def fetch(url):

    resp = session.get(url, timeout=10)
    resp.raise_for_status()
    time.sleep(0.5)

    return BeautifulSoup(resp.content, 'lxml')

The fetch function stops the program on error statuses and returns the parsed page. The pause keeps us from overloading the server.

'url': urljoin(page_url, link['href']),

The parse_card function stores the absolute URL of the detail page, because the card's link is only valid relative to the page where it was found.

Walking the catalogue

With the module in place, the program that walks the pagination is short. We stop after three pages to keep the number of requests low.

catalogue_pages.py
from bookstore import BASE, fetch, next_page, parse_card

url = BASE
books = []

for _ in range(3):

    soup = fetch(url)
    page = soup.select_one('li.current').get_text(strip=True)
    cards = soup.select('article.product_pod')
    books.extend(parse_card(card, url) for card in cards)
    print(f'{page}: {len(cards)} books, {len(books)} in total')

    url = next_page(soup, url)
    if url is None:
        break

top = sorted(books, key=lambda b: (-b['rating'], b['price']))[:3]
for book in top:
    print(book['rating'], book['price'], book['title'])

The program collects the books from the first three catalogue pages and prints the three best rated, cheapest first.

books.extend(parse_card(card, url) for card in cards)

We pass the URL of the current page, so the relative links resolve correctly; the pages are in the catalogue/ directory, while the home page is not.

top = sorted(books, key=lambda b: (-b['rating'], b['price']))[:3]

The key sorts by rating in descending order, and by price for books with the same rating.

$ python catalogue_pages.py
Page 1 of 50: 20 books, 20 in total
Page 2 of 50: 20 books, 40 in total
Page 3 of 50: 20 books, 60 in total
5 15.94 Sophie's World
5 17.27 Thirst
5 17.46 Set Me Free

Scraping a category

The final program combines all steps. It finds the Travel category in the sidebar, collects its books from all of its pages, visits each detail page to get the stock, and saves the result as JSON.

travel_books.py
import json
import re

from bookstore import BASE, fetch, next_page, parse_card


def parse_stock(soup):

    for row in soup.select('table.table-striped tr'):
        if row.th.get_text() == 'Availability':
            return int(re.search(r'\d+', row.td.get_text()).group())

    return 0


soup = fetch(BASE)
link = soup.find('a', string=lambda s: s.strip() == 'Travel')
url = BASE + link['href']

books = []
while url:
    soup = fetch(url)
    for card in soup.select('article.product_pod'):
        books.append(parse_card(card, url))
    url = next_page(soup, url)

for book in books:
    book['stock'] = parse_stock(fetch(book['url']))
    book['price'] = str(book['price'])

with open('travel.json', 'w', encoding='utf-8') as f:
    json.dump(books, f, indent=2, ensure_ascii=False)

print(len(books), 'travel books saved to travel.json')
print('copies in stock:', sum(b['stock'] for b in books))

The program sends one request for the home page, one for the category page, and one for each book.

link = soup.find('a', string=lambda s: s.strip() == 'Travel')
url = BASE + link['href']

The category names in the sidebar are padded with whitespace, so we find the link with a function that strips the string before comparing it.

while url:
    soup = fetch(url)
    for card in soup.select('article.product_pod'):
        books.append(parse_card(card, url))
    url = next_page(soup, url)

A category can span several pages; the loop ends when there is no next link.

book['stock'] = parse_stock(fetch(book['url']))
book['price'] = str(book['price'])

We add the stock from the detail page. The json module cannot serialize Decimal, so we store the price as a string, which keeps it exact.

$ python travel_books.py
11 travel books saved to travel.json
copies in stock: 89
$ head -8 travel.json
[
  {
    "title": "It's Only the Himalayas",
    "price": "45.17",
    "rating": 2,
    "url": "https://books.toscrape.com/catalogue/its-only-the-himalayas_981/index.html",
    "stock": 19
  },

Source

Beautiful Soup documentation
Requests documentation
Books to Scrape

In this article we have scraped an online bookstore with BeautifulSoup. We have fixed the response encoding, extracted data from attributes and classes, converted it to numbers, followed links to detail pages, walked the pagination, and saved the results as JSON. The general techniques are in web scraping, the BeautifulSoup API in BeautifulSoup, and scraping of JavaScript pages in Playwright.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.