I'm drafting a code outline for fetching product information using requests and BeautifulSoup. I need to point out that CSS selectors can be site-specific, so mentioning that is essential. The plan involves parsing the domain from the URL and looping through a list of URLs to find the correct configuration for each site.
In the functions, I want to ensure robust error handling for cases where a selector might not be found. I’m considering creating a function to unify price numbers for comparison, but that could be optional.Implementing price extraction
I'm creating a simple function to extract price numbers from a string, using regular expressions. Though it's not perfect for handling EU decimal formats, it will work. I also plan to include a table print feature.
Additionally, for sites that use JavaScript rendering, mentioning a library like Selenium or Playwright is important, but I won't provide the full script.
I'll structure the final response with prerequisites, code, and guidance on adapting to specific sites without mentioning specifics like Amazon. Below is a minimal, extensible Python script you can adapt to scrape product prices from multiple e‑commerce sites for comparison.
Before using it on real sites, make sure you:
Read and follow each site’s Terms of Service.
Respect robots.txt and local laws.
Keep request rates low so you don’t overload sites.
Prefer official APIs where available.
1. Install dependencies
bash
pip install requests beautifulsoup4
2. Example script: price_compare.py
This script:
Takes product URLs as command-line arguments.
Looks up how to parse each site from a config dictionary.
Extracts product title and price.
Prints a simple comparison table.
python
#!/usr/bin/env python3
import argparse
import re
from dataclasses import dataclass
from typing import Optional, Dict
from urllib.parse import urlparse
import requests
from bs4 import BeautifulSoup
# ---- Configuration for each supported site ----
# You must fill in the right CSS selectors for each site you want to support.
SITE_CONFIG: Dict[str, Dict[str, str]] = {
# Example demo site (Books to Scrape, intended for scraping practice):
# See: http://books.toscrape.com/
"books.toscrape.com": {
"title_selector": "div.product_main h1",
"price_selector": "p.price_color",
},
# Add real sites here after checking their ToS and rules.
# "example.com": {
# "title_selector": "h1.product-title",
# "price_selector": "span.price",
# },
}
@dataclass
class ProductInfo:
site: str
url: str
title: Optional[str]
raw_price: Optional[str]
price_value: Optional[float]
def get_domain(url: str) -> str:
parsed = urlparse(url)
return parsed.netloc.lower()
def fetch_html(url: str) -> str:
# Some sites require a User-Agent header; set a generic, honest one.
headers = {
"User-Agent": "PriceComparisonBot/1.0 (contact: you@example.com)"
}
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
return resp.text
def parse_product(url: str) -> ProductInfo:
domain = get_domain(url)
# Match configuration by domain (supports subdomains)
config_key = None
for key in SITE_CONFIG.keys():
if domain.endswith(key):
config_key = key
break
if not config_key:
return ProductInfo(
site=domain,
url=url,
title=None,
raw_price=None,
price_value=None,
)
html = fetch_html(url)
soup = BeautifulSoup(html, "html.parser")
title_el = soup.select_one(SITE_CONFIG[config_key]["title_selector"])
price_el = soup.select_one(SITE_CONFIG[config_key]["price_selector"])
title = title_el.get_text(strip=True) if title_el else None
raw_price = price_el.get_text(strip=True) if price_el else None
price_value = parse_price(raw_price) if raw_price else None
return ProductInfo(
site=config_key,
url=url,
title=title,
raw_price=raw_price,
price_value=price_value,
)
def parse_price(price_str: str) -> Optional[float]:
"""
Extract a numeric price from a string like '$1,299.99' or '€19.95'.
This is simplistic and may need localization tweaks.
"""
if not price_str:
return None
# Remove currency symbols and any non-digit/., characters
cleaned = re.sub(r"[^\d.,]", "", price_str)
# Handle common formats. This is basic; adjust for your locales.
# Strategy: if there is both '.' and ',', assume '.' is decimal and
# strip commas as thousands separators.
if "." in cleaned and "," in cleaned:
cleaned = cleaned.replace(",", "")
else:
# If only one of them appears, you may need custom rules per site/locale.
cleaned = cleaned.replace(",", "")
try:
return float(cleaned)
except ValueError:
return None
def print_comparison(products):
# Find column widths for basic table formatting
title_width = max(len(p.title or "N/A") for p in products) if products else 10
site_width = max(len(p.site) for p in products) if products else 10
header = f"{'Site'.ljust(site_width)} {'Title'.ljust(title_width)} Price"
print(header)
print("-" * len(header))
for p in products:
price_display = p.raw_price or "N/A"
print(
f"{p.site.ljust(site_width)} "
f"{(p.title or 'N/A')[:title_width].ljust(title_width)} "
f"{price_display}"
)
def main():
parser = argparse.ArgumentParser(
description="Compare product prices from multiple e-commerce URLs."
)
parser.add_argument(
"urls",
nargs="+",
help="Product page URLs to scrape and compare",
)
args = parser.parse_args()
products = []
for url in args.urls:
try:
info = parse_product(url)
except Exception as e:
domain = get_domain(url)
info = ProductInfo(
site=domain,
url=url,
title=None,
raw_price=None,
price_value=None,
)
print(f"Error fetching {url}: {e}")
products.append(info)
print_comparison(products)
if __name__ == "__main__":
main()
3. How to adapt it to real e‑commerce sites
Choose one site and verify you’re allowed to scrape it (ToS, robots.txt).
Open a product page in your browser, inspect the HTML, and find: