🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

Web scraper to CSV

Scrape every book on books.toscrape.com (a site made for scraping practice) into a clean CSV with title, price, rating and stock.

Beginner⏱ 4–6 hoursđŸĒœ 7 stepsPythonrequestsBeautifulSoup

What you'll learn

  • ◆How HTML pages are structured
  • ◆requests and BeautifulSoup selectors
  • ◆Pagination, polite delays and cleaning data

What you'll build

  • ✓Scrapes all 50 pages
  • ✓Extracts title, price, star rating, availability and link
  • ✓Waits between requests
  • ✓Saves to CSV and prints quick stats

Step-by-step guide

  1. 1

    Inspect the page

    Open books.toscrape.com, right-click a book → Inspect. Each book is an article.product_pod with h3 a[title], p.price_color and p.star-rating.

  2. 2

    Fetch one page

    pip install requests beautifulsoup4; r = requests.get(url, timeout=10); soup = BeautifulSoup(r.text, "html.parser").

  3. 3

    Extract fields

    Loop over soup.select("article.product_pod"); read the title attribute, strip "ÂŖ" from the price, map the rating class ("Three") to 3.

  4. 4

    Follow pagination

    Find li.next a; build the next URL with urllib.parse.urljoin and continue until there is no next link.

  5. 5

    Be polite

    Add time.sleep(1) between pages and a clear User-Agent. Always check a site's robots.txt and terms before scraping it.

  6. 6

    Save to CSV

    Write rows with csv.DictWriter; then print the count, average price and number of 5-star books.

  7. 7

    Handle errors

    Retry a failed page up to 3 times with r.raise_for_status() inside try/except requests.RequestException.

🚀 Make it stand out

  • +Visit each book page to collect the category and description
  • +Store results in SQLite and track price changes
  • +Rewrite with Scrapy