Below is a small, self-contained “proof-of-concept” (POC) that, given an Amazon .nl product URL, prints the product title, current price, currency, and description.
⚠️ IMPORTANT LEGAL NOTE
• Amazon’s Terms of Service forbid automated scraping of their pages without explicit prior permission.
• For production use you should enrol in Amazon’s “Product Advertising API” (PA-API) or obtain written permission to scrape.
• This POC is offered strictly for educational purposes so you can test ideas on pages you own or for which you have permission.
─────────────────────────────────────────────
- Why Python?
─────────────────────────────────────────────
• Fastest time-to-POC (batteries included).
• Huge scraping/automation ecosystem (Requests, BeautifulSoup, Playwright, etc.).
• Easy to containerise (Docker) and to extend later with FastAPI, Celery, PostgreSQL, Redis, etc.
─────────────────────────────────────────────
2. Tech stack for the POC
─────────────────────────────────────────────
• Python ≥ 3.10
• Requests – lightweight HTTP client
• BeautifulSoup (lxml parser) – robust HTML parsing
• python-dotenv – handy when you later add env vars (API keys, DB strings, …)
• pytest – quick tests
─────────────────────────────────────────────
3. Project layout
─────────────────────────────────────────────
price-tracker/ # top-level folder
├── README.md
├── pyproject.toml # Poetry project file (or use requirements.txt)
├── .env.example # template for env variables
├── price_tracker/
│ ├── init.py
│ ├── scraper.py # main scraper logic
│ ├── models.py # dataclass for product
│ └── exceptions.py
└── tests/
└── test_scraper.py
(You can of course collapse everything into one file for a super-minimal demo; below I’ll show the “one-file” path first and then the full Poetry setup.)
─────────────────────────────────────────────
4. Quick-&-dirty single-file version
─────────────────────────────────────────────
Create file fetch_amazon.py:
#!/usr/bin/env python3
"""
fetch_amazon.py – tiny POC to extract title, price, description from an Amazon.nl product page
Usage: python fetch_amazon.py https://www.amazon.nl/dp/XXXXXXXXX
"""
from __future__ import annotations
import re, sys, json, dataclasses, logging
import requests
from bs4 import BeautifulSoup
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
@dataclasses.dataclass
class Product:
title: str
price: float
currency: str
description: str
url: str
def _clean_price(raw: str) -> tuple[float, str]:
"""
Convert strings like '€ 79,99' or '€79.99' to (79.99, '€')
"""
currency_match = re.match(r'^\D{1,3}', raw.strip())
currency = currency_match.group(0).strip() if currency_match else ""
numeric = re.sub(r'[^\d,\.]', '', raw) # keep digits , .
# Replace comma as decimal if no dot decimal present
if numeric.count(',') == 1 and numeric.count('.') == 0:
numeric = numeric.replace(',', '.')
# Remove thousand separators
numeric = numeric.replace(',', '')
price_val = float(numeric)
return price_val, currency
def fetch_product(url: str, *, user_agent: str | None = None) -> Product:
headers = {
"User-Agent": user_agent
or "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36"
}
logging.info("Downloading %s", url)
resp = requests.get(url, headers=headers, timeout=15)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "lxml")
# ------- Title -------
title_tag = soup.select_one("#productTitle")
if not title_tag:
raise RuntimeError("Could not locate product title")
title = title_tag.get_text(strip=True)
# ------- Price -------
price_selectors = [
"#priceblock_dealprice",
"#priceblock_ourprice",
"#priceblock_saleprice",
"span.a-price > span.a-offscreen",
]
price_tag = None
for sel in price_selectors:
price_tag = soup.select_one(sel)
if price_tag:
break
if not price_tag:
raise RuntimeError("Could not locate price")
price_raw = price_tag.get_text(strip=True)
price_val, currency = _clean_price(price_raw)
# ------- Description -------
descr_tag = soup.select_one("#productDescription") or soup.select_one("#featurebullets_feature_div")
description = (
descr_tag.get_text(" ", strip=True) if descr_tag else "N/A"
)
return Product(
title=title,
price=price_val,
currency=currency,
description=description,
url=url,
)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python fetch_amazon.py <amazon-product-url>", file=sys.stderr)
sys.exit(1)
product = fetch_product(sys.argv[1])
print(json.dumps(dataclasses.asdict(product), ensure_ascii=False, indent=2))
─────────────────────────────────────────────
5. Installing & running the one-file demo
─────────────────────────────────────────────
# 1. Create & activate virtual env (optional but recommended)
python -m venv venv
source venv/bin/activate # or .\venv\Scripts\activate on Windows
# 2. Install deps
pip install requests beautifulsoup4 lxml
# 3. Run it
python fetch_amazon.py "https://www.amazon.nl/dp/B0C1234567"
Expected JSON:
{
"title": "Logitech MX Master 3S – Advanced Wireless Mouse",
"price": 79.99,
"currency": "€",
"description": "Logitech’s iconic mouse with ...",
"url": "https://www.amazon.nl/dp/B0C1234567"
}
─────────────────────────────────────────────
6. Scalable/cleaner variant with Poetry
─────────────────────────────────────────────
If you prefer a tidier structure ready for CI/CD, packaging, unit tests, etc.:
a) Initialise:
mkdir price-tracker && cd price-tracker
poetry init --name "price-tracker" --python "^3.10" -n
poetry add requests beautifulsoup4 lxml python-dotenv
poetry add --group dev pytest
b) Add the code:
price_tracker/models.py
from dataclasses import dataclass
@dataclass(slots=True)
class Product:
title: str
price: float
currency: str
description: str
url: str
price_tracker/exceptions.py
class ScraperError(RuntimeError):
"""Raised when page structure changes or target unavailable."""
price_tracker/scraper.py
from __future__ import annotations
import logging, re
from bs4 import BeautifulSoup
import requests
from .models import Product
from .exceptions import ScraperError
log = logging.getLogger(__name__)
def _clean_price(raw: str) -> tuple[float, str]:
currency = re.match(r'^\D{1,3}', raw.strip()).group(0).strip()
numeric = re.sub(r'[^\d,\.]', '', raw)
if numeric.count(',') == 1 and numeric.count('.') == 0:
numeric = numeric.replace(',', '.')
numeric = numeric.replace(',', '')
return float(numeric), currency
def fetch_product(url: str, user_agent: str | None = None) -> Product:
headers = {
"User-Agent": user_agent
or "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36"}
log.info("Fetching %s", url)
resp = requests.get(url, headers=headers, timeout=15)
if resp.status_code >= 400:
raise ScraperError(f"HTTP {resp.status_code}")
soup = BeautifulSoup(resp.text, "lxml")
title_tag = soup.select_one("#productTitle")
if not title_tag:
raise ScraperError("Title not found")
title = title_tag.get_text(strip=True)
price_tag = next(
(soup.select_one(sel)
for sel in ("#priceblock_dealprice",
"#priceblock_ourprice",
"#priceblock_saleprice",
"span.a-price > span.a-offscreen")
if soup.select_one(sel)),
None)
if not price_tag:
raise ScraperError("Price not found")
price, currency = _clean_price(price_tag.text)
descr_tag = soup.select_one("#productDescription")
description = descr_tag.get_text(" ", strip=True) if descr_tag else "N/A"
return Product(title, price, currency, description, url)
CLI wrapper (optional) price_tracker/__main__.py
import argparse, json, dataclasses
from .scraper import fetch_product
def main():
ap = argparse.ArgumentParser()
ap.add_argument("url", help="Amazon.nl product URL")
args = ap.parse_args()
product = fetch_product(args.url)
print(json.dumps(dataclasses.asdict(product), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
Run:
poetry run python -m price_tracker "https://www.amazon.nl/dp/B0C1234567"
Tests:
tests/test_scraper.py
from price_tracker.scraper import _clean_price
def test_clean_price():
assert _clean_price("€ 79,99") == (79.99, "€")
poetry run pytest -q should pass.
─────────────────────────────────────────────
7. Next steps towards the full product-tracker
─────────────────────────────────────────────
- Switch to official Amazon PA-API to stay compliant and avoid being blocked.
- Store product entities + historical price snapshots in PostgreSQL.
- Schedule periodic jobs (Celery + redis or apscheduler).
- Provide REST + WebSocket API (FastAPI) and/or a small React/Vue front-end.
- Add user accounts, auth, thresholds, and email/push notification integration (SendGrid, Firebase, …).
- Headless browser fallback (Playwright) for sites that rely heavily on JS.
─────────────────────────────────────────────
8. Closing
─────────────────────────────────────────────
You now have a fully working POC that can be executed in a few minutes, plus a roadmap for turning it into a production-grade multi-site price tracker. Remember to respect each retailer’s robots.txt and terms of service—or, better yet, use their official APIs whenever available. Happy coding! 🛠️💸