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.
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
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
Fetch one page
pip install requests beautifulsoup4; r = requests.get(url, timeout=10); soup = BeautifulSoup(r.text, "html.parser").
- 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
Follow pagination
Find li.next a; build the next URL with urllib.parse.urljoin and continue until there is no next link.
- 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
Save to CSV
Write rows with csv.DictWriter; then print the count, average price and number of 5-star books.
- 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