Clarifying the Objective
I'm now zeroing in on the core goal: building a Python script to scrape data from e-commerce websites. This is the foundational step, guiding all subsequent design choices. The aim is to make it robust and efficient.
Refining the Scope
I'm now zeroing in on product title and price extraction for price comparisons. I've identified crucial challenges: dynamic content loading on e-commerce sites, robust anti-scraping measures to evade detection, and the need for site-specific logic to parse the diverse HTML structures. I'll start with a modular requests and BeautifulSoup (bs4) script, aiming for broad applicability and incorporating these considerations from the start.
Formulating the Prototype
I'm solidifying the prototype's structure. It'll feature requests for fetching, BeautifulSoup (bs4) for parsing, and pandas for handling data. Error handling is paramount in the fetcher function. Parsing functions will vary per website to extract titles and prices, necessitating cleaning for price data. The main logic will integrate these components, outputting a CSV file.
Building the Core Script
I'm now building the actual Python script, focusing on data extraction from the "Books to Scrape" sandbox website. I'm using requests and BeautifulSoup to handle the HTTP requests and parsing, and pandas for structure. I've defined the target URL and extraction logic for product titles, prices, and availability, including price cleaning by removing the "£" character. I'm iteratively refining it as I go.
Designing Extensibility & Ethics
I've revised the prototype's scope. To simulate a comparison, I'll scrape different categories from books.toscrape.com, ensuring the data structure's adaptability. While initially focusing on that site, the code will be extensible for Amazon and eBay, with commented-out selectors. I'm also integrating best practices: mentioning robots.txt, implementing rate limiting (using time.sleep), and setting a proper User-Agent string. Now, I'm ready for the final code assembly, using a class-based structure for organization.
Concluding the Script
I've completed the script, refining the extraction logic for output to a Pandas DataFrame. I've re-evaluated the code against the user's initial request for a price comparison tool, confirming that it addresses the core requirements. I'm now crafting a clear explanation of the script's functionality, including installation instructions and code section descriptions, with a critical warning about the limitations of basic scraping against more robust sites like Amazon. Finally, I'm performing a final review for any indentation or variable naming inconsistencies, and ensuring the price-cleaning regex is robust. I'm ready to present the final solution.
This is a complex task because every e-commerce website (Amazon, eBay, Walmart) has a completely different HTML structure. Furthermore, major sites have aggressive anti-scraping measures (CAPTCHAs, IP bans).
Below is a robust, modular Python script using requests and BeautifulSoup.
The Approach
- Modular Design: I have separated the "fetching" logic from the "parsing" logic.
- Demonstration Strategy: To guarantee this script runs successfully for you immediately, it targets Books to Scrape (a sandbox website specifically built for testing scrapers).
- Extensibility: I included a commented-out template showing how you would adapt the code for a site like Amazon.
1. Prerequisites
You will need to install the following libraries:
pip install requests beautifulsoup4 pandas
2. The Python Script
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import random
import re
class PriceScraper:
def __init__(self):
# Headers are crucial to mimic a real browser and avoid 403 Forbidden errors
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.9'
}
self.data = []
def clean_price(self, price_str):
"""
Extracts numerical value from strings like '£51.77', '$1,200.00'
"""
# Remove non-numeric chars except '.' and ','
clean_str = re.sub(r'[^\d.,]', '', price_str)
try:
return float(clean_str.replace(',', ''))
except ValueError:
return 0.0
def fetch_page(self, url):
"""
Fetches the HTML content of a page with error handling
"""
try:
print(f"Fetching: {url}")
response = requests.get(url, headers=self.headers, timeout=10)
response.raise_for_status()
# Sleep randomly to be polite and avoid bot detection
time.sleep(random.uniform(1, 3))
return response.content
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
def parse_books_to_scrape(self, url):
"""
Logic specifically for books.toscrape.com
"""
html = self.fetch_page(url)
if not html: return
soup = BeautifulSoup(html, 'html.parser')
products = soup.select('article.product_pod')
for product in products:
# Extract specific elements based on HTML inspection
title = product.h3.a['title']
price_text = product.select_one('.price_color').text
price = self.clean_price(price_text)
# Check stock
availability = product.select_one('.instock.availability').text.strip()
self.data.append({
'source': 'BooksToScrape',
'title': title,
'price': price,
'currency': 'GBP',
'availability': availability,
'url': 'http://books.toscrape.com/' + product.h3.a['href']
})
def parse_amazon_style(self, url):
"""
TEMPLATE: Logic for an Amazon-style structure.
Note: Amazon often requires Selenium due to heavy anti-bot protection.
"""
html = self.fetch_page(url)
if not html: return
soup = BeautifulSoup(html, 'html.parser')
# Example Selectors (These change frequently on real sites)
# This is just to show how you would add a new site
try:
title = soup.select_one('#productTitle').text.strip()
price_text = soup.select_one('.a-price-whole').text.strip()
price = self.clean_price(price_text)
self.data.append({
'source': 'Amazon',
'title': title,
'price': price,
'currency': 'USD',
'availability': 'Check Site',
'url': url
})
except AttributeError:
print("Could not parse product details for Amazon URL")
def run(self):
# Example 1: Scrape a catalog page (Books To Scrape)
self.parse_books_to_scrape('http://books.toscrape.com/catalogue/category/books/travel_2/index.html')
self.parse_books_to_scrape('http://books.toscrape.com/catalogue/category/books/mystery_3/index.html')
# Example 2: Add logical comparison (Pseudo-code for real implementation)
# self.parse_amazon_style('https://amazon.com/dp/someproduct')
# self.parse_ebay_style('https://ebay.com/itm/someproduct')
# Save to DataFrame
df = pd.DataFrame(self.data)
if not df.empty:
# Sort by price to help with comparison
df_sorted = df.sort_values(by='price')
print("\n--- Scraped Data (Sorted by Price) ---")
print(df_sorted[['title', 'price', 'source']].head(10))
# Export to CSV
df_sorted.to_csv('price_comparison.csv', index=False)
print("\nSaved to price_comparison.csv")
else:
print("No data found.")
if __name__ == "__main__":
scraper = PriceScraper()
scraper.run()
How to customize this for Real Sites (Amazon/eBay)
The script above works perfectly on the test site. To make it work on real sites, you must inspect the HTML of the target site.
- Right-click the price on the website and select Inspect.
- Look for the
class or id.
- Example: If the price is in
<span class="a-price">$50.00</span>, your selector is .a-price.
- Create a new function in the class (e.g.,
parse_bestbuy) and update the selectors:
# Inside a new function
title = soup.select_one('h1.heading-5').text # Hypothetical BestBuy selector
price = soup.select_one('.priceView-customer-price span').text
Challenges using this on Real Sites
If you try to scrape Amazon or Walmart with the script above, you might get blocked quickly. Here is why and how to fix it:
- JavaScript Rendering: Modern sites (like Nike or Walmart) load prices using JavaScript.
requests cannot read this.
- Solution: Use Selenium or Playwright. These tools launch a real (headless) Chrome browser that executes JavaScript.
- Bot Detection: Sites check your "User Agent" and IP address.
- Solution: You need to rotate User-Agents (libraries like
fake-useragent) and use Proxy Rotation (services like BrightData or ScraperAPI).
Advanced: Switching to Selenium (For Dynamic Sites)
If requests returns empty data, replace the fetch_page logic with this:
# Requires: pip install selenium webdriver-manager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
def fetch_dynamic_page(url):
options = webdriver.ChromeOptions()
options.add_argument('--headless') # Run in background
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.get(url)
html = driver.page_source
driver.quit()
return html