How to Build an Amazon Price Tracker with Python — Step by Step

By Daniel Reeves Software Engineer & Ecommerce Technology Writer at Priceva
Automation & AI · Marketplaces · Published on November 18, 2026 · 7 min read
An Amazon price tracker in Python is a script that checks a product page on a schedule, extracts the current price, stores each reading, and alerts when the price reaches a useful threshold. For developers and small ecommerce businesses, building a tracker from scratch is a practical way to understand how Amazon web scraping, historical price storage, scheduling, and notifications fit together since commissions and margin are included in the "build or buy" decision. A small DIY tracker can work well for a handful of products, especially when custom logic or integration with another internal system matters more than having a polished dashboard. This guide builds the core workflow step by step and also covers the point many tutorials overlook: when maintaining a custom scraper starts costing more than using a managed price-monitoring platform.

What Is an Amazon Price Tracker — and What Does It Need to Do?

At minimum, a useful price-monitoring script has three jobs: extract, store, and alert. Extraction means obtaining the current offer price from the product source being monitored. Storage turns individual observations into price history, while the alert layer compares the latest observation with a target or previous value and decides whether someone needs to know about the change. Without all three components, an Amazon price tracking script is usually either a one-time scraper or a pile of historical data that nobody acts on.

Existing services such as Keepa and CamelCamelCamel already provide Amazon price history and consumer price-drop notifications, so rebuilding that basic consumer experience is rarely necessary. A custom tracker makes more sense when the goal is to control the data model, apply a custom threshold, combine results with another database, or experiment with monitoring logic. Businesses face a different problem again: dozens or hundreds of ASINs create matching, monitoring-frequency, reliability, and maintenance requirements that a personal script was never designed to solve. That distinction becomes important later when comparing the total cost of a DIY build with catalog-scale monitoring.

Conceptually, the workflow is simple:

Amazon product page → extract current price → validate it → save timestamped observation → compare with threshold/history → send alert

The difficulty is not the workflow itself. The difficult part is keeping extraction reliable when page layouts differ, network requests fail, product offers change, or Amazon changes its markup. A robust tracker therefore needs fallback logic and explicit failure handling rather than assuming that one CSS selector will work forever.

Prerequisites and Project Setup

The examples below use Python, requests for HTTP requests, Beautiful Soup for HTML parsing, pandas for simple price-history storage, schedule for recurring checks, and Matplotlib for optional visualization. Although the basic syntax would work on several older Python 3 releases, Python 3.11 or newer is the better starting point in 2026 because Python 3.8 reached end of life in October 2024 and Python 3.10 reached end of life in October 2026. Using a currently supported release reduces unnecessary dependency and security problems before the project even starts.

Create a dedicated directory and virtual environment so that the dependencies remain isolated from other Python projects. The commands differ slightly between Unix-based systems and Windows, but the resulting environment works the same way. A virtual environment also makes the tracker easier to move to a small server later because its package requirements can be reproduced without modifying the system Python installation. For a project this small, there is no need to introduce Docker, a web framework, or a database server at the beginning.
mkdir amazon-price-tracker
cd amazon-price-tracker

python3 -m venv .venv

# macOS / Linux
source .venv/bin/activate

# Windows PowerShell
.venv\Scripts\Activate.ps1

pip install requests beautifulsoup4 pandas schedule matplotlib
The examples below use Python, requests for HTTP requests, Beautiful Soup for HTML parsing, pandas for simple price-history storage, schedule for recurring checks, and Matplotlib for optional visualization. Although the basic syntax would work on several older Python 3 releases, Python 3.11 or newer is the better starting point in 2026 because Python 3.8 reached end of life in October 2024 and Python 3.10 reached end of life in October 2026. Using a currently supported release reduces unnecessary dependency and security problems before the project even starts.

Create a dedicated directory and virtual environment so that the dependencies remain isolated from other Python projects. The commands differ slightly between Unix-based systems and Windows, but the resulting environment works the same way. A virtual environment also makes the tracker easier to move to a small server later because its package requirements can be reproduced without modifying the system Python installation. For a project this small, there is no need to introduce Docker, a web framework, or a database server at the beginning.
A minimal project can begin with one tracker.py file and a generated price_history.csv. As the code grows, email configuration, storage logic, and scraping logic can be moved into separate modules, but that separation adds little value during the first working iteration. The goal at this stage is to prove that one product can be extracted reliably before attempting scheduling or multi-product monitoring. That approach makes troubleshooting much easier because each additional layer is added only after the previous one works.

Step 1 — Understand Amazon's Page Structure

Every Amazon catalog product has an ASIN, or Amazon Standard Identification Number, which is a unique 10-character identifier. A typical product URL contains it after /dp/, so a long URL containing referral and tracking parameters can usually be reduced to a cleaner structure such as https://www.amazon.com/dp/B0XXXXXXXX. The ASIN is more useful than the full browsing URL because it provides a stable identifier for storing historical observations and joining them with other datasets. Amazon itself defines the ASIN as a 10-character alphanumeric identifier assigned to products in its catalog.

The visible price is less stable than the product identifier. Older Python tutorials frequently rely on IDs such as priceblock_ourprice, but that pattern belongs to older Amazon page layouts and should not be treated as a current selector. Current product pages commonly expose a complete formatted price inside a screen-reader element using the a-offscreen class, often within containers such as corePriceDisplay_desktop_feature_div or corePrice_feature_div. Recent technical checks of Amazon product markup continue to find a-offscreen within the main price block, but Amazon's DOM is not a public API and can change again.

That is why an Amazon web scraping script should use a short selector chain rather than one hardcoded element. The important word is scoped: a plain page-wide span.a-offscreen can also match unrelated prices in recommendations, subscription offers, or other seller modules. It is safer to search the primary price containers first and report a failure when none matches than to silently save the wrong price. The same principle applies to the title, where #productTitle remains a useful anchor but should still be checked for None before the text is accessed.

Step 2 — Write the Core Scraper

The core scraper needs to request the product page, confirm that a usable response was returned, extract the product title, and test several price locations in order. The example below deliberately separates parse_price() from scrape_product() so that currency-text parsing can be tested independently from network behavior. It also uses Decimal instead of float, because binary floating-point numbers are a poor representation for exact monetary values. The result is still a small script, but it already avoids several failure modes common in one-selector tutorials.
import re
from decimal import Decimal, InvalidOperation

import requests
from bs4 import BeautifulSoup


HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/155.0.0.0 Safari/537.36"
    ),
    "Accept-Language": "en-US,en;q=0.9",
    "Accept": (
        "text/html,application/xhtml+xml,application/xml;q=0.9,"
        "image/avif,image/webp,*/*;q=0.8"
    ),
}

PRICE_SELECTORS = [
    "#corePriceDisplay_desktop_feature_div span.a-offscreen",
    "#corePrice_feature_div span.a-offscreen",
    "span.priceToPay span.a-offscreen",
    ".apexPriceToPay span.a-offscreen",
]


def parse_price(text: str) -> Decimal:
    cleaned = re.sub(r"[^\d,.\-]", "", text.strip())

    if not cleaned:
        raise ValueError(f"No numeric price found in {text!r}")

    # Handles formats such as:
    # 1,299.99
    # 1.299,99
    # 29,99
    # 1,299
    if "," in cleaned and "." in cleaned:
        decimal_separator = (
            "," if cleaned.rfind(",") > cleaned.rfind(".") else "."
        )
        thousands_separator = "." if decimal_separator == "," else ","
        cleaned = cleaned.replace(thousands_separator, "")
        cleaned = cleaned.replace(decimal_separator, ".")

    elif "," in cleaned:
        parts = cleaned.split(",")
        if len(parts[-1]) in (1, 2):
            cleaned = "".join(parts[:-1]) + "." + parts[-1]
        else:
            cleaned = "".join(parts)

    elif "." in cleaned:
        parts = cleaned.split(".")
        if len(parts) > 2 or len(parts[-1]) == 3:
            cleaned = "".join(parts)

    try:
        return Decimal(cleaned)
    except InvalidOperation as exc:
        raise ValueError(f"Could not parse price: {text!r}") from exc


def scrape_product(url: str) -> dict:
    response = requests.get(
        url,
        headers=HEADERS,
        timeout=20,
    )
    response.raise_for_status()

    soup = BeautifulSoup(response.text, "html.parser")

    title_element = soup.select_one("#productTitle")
    if title_element is None:
        raise RuntimeError("Product title was not found.")

    price_element = None
    matched_selector = None

    for selector in PRICE_SELECTORS:
        candidate = soup.select_one(selector)
        if candidate and candidate.get_text(strip=True):
            price_element = candidate
            matched_selector = selector
            break

    if price_element is None:
        raise RuntimeError(
            "No main product price was found. "
            "The page layout may have changed."
        )

    return {
        "title": title_element.get_text(" ", strip=True),
        "price": parse_price(price_element.get_text(strip=True)),
        "selector": matched_selector,
        "url": url,
    }


if __name__ == "__main__":
    product = scrape_product(
        "https://www.amazon.com/dp/YOUR_ASIN_HERE"
    )
    print(product)
This code intentionally does not use a bare span.a-offscreen as the automatic final fallback. Many Amazon modules use the same accessibility class, meaning a global match can return the wrong amount while still looking perfectly valid to the parser. A tracker that saves no price is inconvenient, but a tracker that silently saves a recommendation-carousel price as the main product price is substantially worse. Recent scraping research makes the same point: a-offscreen is useful, but it should be scoped to the relevant price container whenever possible. The core scraper should do more than send one HTTP request and hope for a valid product page. To scrape Amazon prices reliably enough for a scheduled tracker, the request layer needs to handle temporary failures before the HTML is passed to Beautiful Soup. The implementation below creates a reusable requests.Session, adds exponential backoff for 429 Too Many Requests and 503 Service Unavailable responses, and checks whether Amazon returned a CAPTCHA or Robot Check page instead of normal product HTML. Connecting those functions here, rather than leaving them as an isolated example later in the article, makes the code work as one complete system when the scheduler is added in Step 5.

Start with the request configuration, retry-enabled session, and HTML-fetching function. Retry controls how temporary failures are retried, while respect_retry_after_header=True allows the client to follow a server-provided delay when one is available. After the retry policy finishes, fetch_html() still validates the final status code before returning the response body. It also stops immediately when the returned HTML appears to be an access-control page, which prevents the parser from treating a CAPTCHA as if Amazon had simply removed the price.
import re
from decimal import Decimal, InvalidOperation

from bs4 import BeautifulSoup
from requests import Session
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry


HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/155.0.0.0 Safari/537.36"
    ),
    "Accept-Language": "en-US,en;q=0.9",
    "Accept": (
        "text/html,application/xhtml+xml,application/xml;q=0.9,"
        "image/avif,image/webp,*/*;q=0.8"
    ),
}

PRICE_SELECTORS = [
    "#corePriceDisplay_desktop_feature_div span.a-offscreen",
    "#corePrice_feature_div span.a-offscreen",
    "span.priceToPay span.a-offscreen",
    ".apexPriceToPay span.a-offscreen",
]


def build_session() -> Session:
    retry_policy = Retry(
        total=4,
        connect=3,
        read=3,
        status=4,
        backoff_factor=2,
        status_forcelist=(429, 503),
        allowed_methods=frozenset(["GET"]),
        respect_retry_after_header=True,
        raise_on_status=False,
    )

    adapter = HTTPAdapter(
        max_retries=retry_policy,
        pool_connections=10,
        pool_maxsize=10,
    )

    session = Session()
    session.mount("https://", adapter)
    session.mount("http://", adapter)

    return session


def fetch_html(url: str, session: Session) -> str:
    response = session.get(
        url,
        headers=HEADERS,
        timeout=20,
    )

    if response.status_code >= 400:
        raise RuntimeError(
            f"HTTP {response.status_code} for {url}"
        )

    html = response.text
    lower_html = html.lower()

    if "captcha" in lower_html or "robot check" in lower_html:
        raise RuntimeError(
            "Amazon returned an access-control page. "
            "Stop this check and review the access method."
        )

    return html
The next function handles price text separately from the network request. Using Decimal instead of float avoids binary floating-point rounding when prices later feed into thresholds, percentage calculations, or historical comparisons. The parser also accounts for common comma-and-period conventions rather than assuming that every Amazon marketplace formats prices exactly like Amazon.com. Keeping this logic isolated makes it easier to test price parsing without repeatedly requesting a live product page.
def parse_price(text: str) -> Decimal:
    cleaned = re.sub(r"[^\d,.\-]", "", text.strip())

    if not cleaned:
        raise ValueError(f"No numeric price found in {text!r}")

    # Handles formats such as:
    # 1,299.99
    # 1.299,99
    # 29,99
    # 1,299
    if "," in cleaned and "." in cleaned:
        decimal_separator = (
            "," if cleaned.rfind(",") > cleaned.rfind(".") else "."
        )
        thousands_separator = (
            "." if decimal_separator == "," else ","
        )
        cleaned = cleaned.replace(thousands_separator, "")
        cleaned = cleaned.replace(decimal_separator, ".")

    elif "," in cleaned:
        parts = cleaned.split(",")

        if len(parts[-1]) in (1, 2):
            cleaned = "".join(parts[:-1]) + "." + parts[-1]
        else:
            cleaned = "".join(parts)

    elif "." in cleaned:
        parts = cleaned.split(".")

        if len(parts) > 2 or len(parts[-1]) == 3:
            cleaned = "".join(parts)

    try:
        return Decimal(cleaned)
    except InvalidOperation as exc:
        raise ValueError(
            f"Could not parse price: {text!r}"
        ) from exc
The final part connects fetching and parsing into the function used throughout the rest of the project. scrape_product() now receives the reusable session as an argument and obtains its HTML only through fetch_html(). This means every scheduled request automatically uses the retry policy, HTTP-status handling, and CAPTCHA detection defined above. Anyone following the tutorial to build price tracker functionality therefore ends up with one request path rather than a basic scraper in Step 2 and a disconnected retry example several sections later.
def scrape_product(
    url: str,
    session: Session,
) -> dict:
    html = fetch_html(url, session)
    soup = BeautifulSoup(html, "html.parser")

    title_element = soup.select_one("#productTitle")

    if title_element is None:
        raise RuntimeError(
            "Product title was not found."
        )

    price_element = None
    matched_selector = None

    for selector in PRICE_SELECTORS:
        candidate = soup.select_one(selector)

        if candidate and candidate.get_text(strip=True):
            price_element = candidate
            matched_selector = selector
            break

    if price_element is None:
        raise RuntimeError(
            "No main product price was found. "
            "The page layout may have changed."
        )

    return {
        "title": title_element.get_text(" ", strip=True),
        "price": parse_price(
            price_element.get_text(strip=True)
        ),
        "selector": matched_selector,
        "url": url,
    }
This code intentionally does not use a bare span.a-offscreen as the automatic final fallback. Amazon can use the same accessibility class for several monetary values on one page, so an unrestricted selector may return a recommendation, subscription price, or alternative offer rather than the main product price. A missing value is easier to diagnose than a plausible but incorrect value stored silently in price history. Scoped selectors therefore provide a safer starting point even though they still need maintenance when Amazon changes its markup.

Why the User-Agent and Headers Matter

HTTP headers affect which representation of a page a server returns, so a request with no language or browser context can produce different markup from an ordinary browser session. A conventional User-Agent and Accept-Language header also make debugging more predictable because the returned page is more likely to use the expected language and number formatting. They should not be treated as a guarantee against rate limits, CAPTCHA challenges, or other access controls. If automated access is restricted, changing HTTP headers does not create permission to collect the data.

Parsing Price Text Safely with Decimal

float("$19.99") does not work directly, and even a cleaned 19.99 should not be the default monetary representation for price calculations. Decimal("19.99") represents the monetary value exactly, which matters when the tracker later calculates thresholds, percentage changes, or historical lows. The parser above also normalizes common comma-and-period combinations before constructing the Decimal. Currency should still be stored separately when several Amazon marketplaces are monitored because identical numbers in USD, GBP, and EUR do not represent the same economic value.

Step 3 — Store Price History

A current price without history answers only one question: what does the offer cost right now? A genuine price tracker needs a time series so that the latest observation can be compared with yesterday, last week, the historical minimum, or a user-defined reference point. For a small project, CSV is usually the right first storage format because it requires no database setup and can be opened directly in Excel, Google Sheets, pandas, or almost any analytics tool. Each row should include at least the timestamp, product identifier, title, price, currency, and source URL.

The following function appends one observation without loading and rewriting the entire historical file. Timestamps are stored in UTC to prevent later confusion when a script moves between machines or monitors several geographic markets. The ASIN is stored separately from the URL because URLs may be cleaned or changed later while the product identifier remains useful for grouping observations. A currency column is included even if the first version tracks only Amazon.com, which avoids a painful schema change when international marketplaces are added.
from datetime import datetime, timezone
from pathlib import Path

import pandas as pd


def append_history(
    product: dict,
    asin: str,
    currency: str = "USD",
    csv_path: str = "price_history.csv",
) -> None:
    row = pd.DataFrame(
        [
            {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "asin": asin,
                "title": product["title"],
                "price": str(product["price"]),
                "currency": currency,
                "url": product["url"],
                "selector": product["selector"],
            }
        ]
    )

    file_exists = Path(csv_path).exists()

    row.to_csv(
        csv_path,
        mode="a",
        header=not file_exists,
        index=False,
    )
There is no magical file-size threshold at which CSV stops working, but roughly 15–30 actively tracked products is a useful planning point for reconsidering storage architecture. The reason is not that 31 products are too large for a CSV; even thousands of rows are trivial. The problems appear when several jobs need to write simultaneously, queries become more complex, or the script needs transactional updates and indexed lookups. SQLite is an excellent next step because it remains a single local file, while PostgreSQL makes more sense when several services, users, or machines need concurrent access.

Step 4 — Add Price-Drop Email Alerts

Logging every price change is useful for analysis, but a practical Amazon price tracking script should also decide when a change is worth attention. One simple rule is to alert when the current value falls at or below a target price supplied for that ASIN. Another is to compare the latest observation with the previous value and alert only when the percentage drop exceeds a threshold. The first version below uses a target because it is easy to understand, test, and modify without introducing more historical-query logic.

Python includes smtplib, so no external email package is required. Gmail can still be used with an App Password when 2-Step Verification is enabled and the account is eligible for App Passwords, although Google now recommends modern Sign in with Google/OAuth flows where possible. Google describes an App Password as a separate 16-digit credential and notes that some organizational, security-key-only, or Advanced Protection accounts may not expose the option. For a small local script, an App Password remains straightforward; for a production service, OAuth or a dedicated transactional-email provider is a better long-term design.
import os
import smtplib
from decimal import Decimal
from email.message import EmailMessage


def send_price_alert(product: dict, target_price: Decimal) -> None:
    sender = os.environ["TRACKER_EMAIL"]
    app_password = os.environ["TRACKER_EMAIL_APP_PASSWORD"]
    recipient = os.environ["TRACKER_ALERT_TO"]

    message = EmailMessage()
    message["Subject"] = (
        f"Price alert: {product['title'][:60]}"
    )
    message["From"] = sender
    message["To"] = recipient

    message.set_content(
        f"""The tracked Amazon price reached the target.

Product: {product['title']}
Current price: {product['price']}
Target price: {target_price}
URL: {product['url']}
"""
    )

    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
        smtp.login(sender, app_password)
        smtp.send_message(message)


def check_target(product: dict, target_price: Decimal) -> None:
    if product["price"] <= target_price:
        send_price_alert(product, target_price)
The important security rule is that the email address, recipient, and App Password should never be hardcoded into a script that might later be committed to GitHub or shared with another person. Environment variables keep credentials out of the source file and allow different machines to use different configuration. They are not a complete secrets-management solution, but they are substantially safer than writing a live password next to smtp.login(). The same pattern should later be used for database credentials, API keys, or webhook secrets.

Setting Environment Variables — and Remembering to Re-set Them

For a temporary macOS or Linux shell session, variables can be created with commands such as export TRACKER_EMAIL="..."; PowerShell uses $env:TRACKER_EMAIL="...". Session variables disappear when that terminal session ends, which is a common reason a script works during setup and fails after a reboot. Persistent local configuration can instead be loaded through the shell profile, a protected .env mechanism, the operating system's secret store, or the service manager that starts the scheduled process. Whatever method is used, secret files should be excluded from version control.

Running the script manually defeats the main purpose of an Amazon price tracking script. The lightweight schedule package is enough for a learning project or a process that stays active on a local machine or small VPS. For most ordinary products, checking once every 6–12 hours provides a reasonable starting point without repeatedly requesting a page whose price may not have changed. Faster monitoring can be justified for genuinely time-sensitive situations, but the interval should reflect how quickly the resulting price information can actually be used.

The important detail is that the scheduler must use the same retry-enabled session created in Step 2. The code below creates SESSION = build_session() once and passes it into every call to scrape_product(). As a result, each scheduled check follows the complete path run_check() → scrape_product() → fetch_html() → session.get(), rather than bypassing the retry layer with a direct requests.get(). Successful results continue into storage and alerting, while failed checks are logged and left for the next scheduled run.
import time
from decimal import Decimal

import schedule


PRODUCT_URL = "https://www.amazon.com/dp/YOUR_ASIN_HERE"
ASIN = "YOUR_ASIN"
TARGET_PRICE = Decimal("299.99")

SESSION = build_session()


def run_check():
    try:
        product = scrape_product(
            PRODUCT_URL,
            SESSION,
        )

        append_history(
            product,
            ASIN,
            "USD",
        )

        check_target(
            product,
            TARGET_PRICE,
        )

        print(
            f"Checked {ASIN}: "
            f"{product['price']} "
            f"at {product['selector']}"
        )

    except Exception as exc:
        print(
            f"Check failed for {ASIN}: {exc}"
        )


if __name__ == "__main__":
    run_check()

    schedule.every(8).hours.do(run_check)

    while True:
        schedule.run_pending()
        time.sleep(30)
This arrangement also reuses the HTTP connection pool instead of creating an entirely new session for every scheduled request. More importantly, it guarantees that the networking behavior described in the article is actually part of the code readers assemble from the individual steps. If Amazon returns repeated 429 or 503 responses, the session applies bounded backoff before the check fails. If the returned HTML contains an obvious CAPTCHA or Robot Check page, fetch_html() stops the pipeline before invalid content reaches the price parser.

One limitation is that schedule works only while the Python process remains alive. Closing the terminal, rebooting the machine, or crashing the process stops future jobs unless another service starts it again. That is acceptable for a learning project, but a production tracker should eventually run under cron, systemd, Windows Task Scheduler, a cloud scheduler, or another process-management layer. Improving restartability and observability is usually more useful than simply shortening the monitoring interval.

Step 5 — Automate with Scheduling

An Amazon price tracker Python project becomes a tracker only when checks happen without someone manually running the file. The lightweight schedule package is sufficient for an experiment or a process running continuously on a small computer or VPS. It executes a function at the configured interval and then sleeps until the next pending job. For a more permanent deployment, cron, systemd timers, Windows Task Scheduler, a cloud scheduler, or a proper job queue is more resilient because the schedule survives a Python process restart.

For most non-urgent products, one check every 6–12 hours is a sensible starting interval, not a universal Amazon rule. That provides two to four observations per day without hammering the source simply to rediscover the same price repeatedly. High-frequency monitoring may be justified during a short flash-sale or launch window, but it increases request volume and operational risk quickly. The correct interval should be driven by how fast a business could realistically act on a change, not by how frequently a loop can technically run.
import time
from decimal import Decimal

import schedule


PRODUCT_URL = "https://www.amazon.com/dp/YOUR_ASIN_HERE"
ASIN = "YOUR_ASIN"
TARGET_PRICE = Decimal("299.99")


def run_check():
    try:
        product = scrape_product(PRODUCT_URL)
        append_history(product, ASIN, "USD")
        check_target(product, TARGET_PRICE)

        print(
            f"Checked {ASIN}: "
            f"{product['price']} at {product['selector']}"
        )

    except Exception as exc:
        print(f"Check failed for {ASIN}: {exc}")


schedule.every(8).hours.do(run_check)

run_check()

while True:
    schedule.run_pending()
    time.sleep(30)
One subtle limitation is that schedule works only while this Python process remains alive. Closing the terminal, rebooting the machine, or crashing the process stops future jobs unless another service restarts it. That is acceptable for a learning project but should be addressed before depending on the tracker commercially. Reliability usually improves more by making the job restartable and observable than by shortening the scraping interval.

Step 6 — Handle Amazon's Anti-Bot Measures

The retry and access-control logic for this step is already part of the working scraper rather than being introduced as a separate code fragment. Every scheduled request now travels through the retry-enabled Session created in Step 2, so temporary HTTP 429 Too Many Requests and 503 Service Unavailable responses trigger bounded retries with exponential backoff. With backoff_factor=2, repeated failures are spaced progressively farther apart rather than being retried immediately. The configuration also respects a Retry-After response header when the server provides one.

CAPTCHA and Robot Check responses require different handling from ordinary temporary HTTP failures. fetch_html() checks the returned document before the content reaches Beautiful Soup and raises a clear exception when it detects an obvious access-control page. The scheduled run_check() function then logs that failure instead of saving a false price or crashing the scheduling loop. This creates a clean distinction between a product whose price selector has changed and a request that never received a normal product page in the first place.

The same distinction is useful when debugging other failures. A 429 or 503 may be temporary and worth retrying, while a repeated CAPTCHA is a signal to stop the current extraction attempt and review the access method rather than sending more requests immediately. An ordinary 200 response with no matching price selector points to a different class of problem, such as changed markup or a different product-page layout. Reliable scraping therefore depends as much on knowing why a request failed as on retrying it.

User-Agent rotation is sometimes presented as a universal solution to blocking, but it does not fix excessive request frequency, broken selectors, or contractual restrictions on automated access. For a permitted monitoring implementation, conservative scheduling, bounded retries, logging, caching, and clear error states are easier to operate than increasingly complex attempts to disguise requests. An official or licensed data source should also be considered when it fits the intended use case. The goal of the tracker is dependable pricing data, not simply maximizing the number of HTTP requests that receive a 200 response.

Residential vs. Datacenter Proxies

A proxy changes where a request exits to the internet, and legitimate uses can include regional testing or approved data collection across several geographic markets. Datacenter proxies originate from hosting infrastructure and are generally cheaper, faster, and easier to provision at scale. Residential proxies use addresses associated with consumer ISP networks and can better represent what a retail site displays in a particular location, but they usually cost more and require careful attention to provider sourcing, privacy, and contractual compliance. Neither category turns restricted automated collection into permitted collection, so proxy infrastructure should be treated as a networking decision rather than as a method for bypassing access controls.

Step 7 — Optional: Visualize Price History

Once several days or weeks of readings have accumulated, a line chart makes an Amazon price tracking dataset much easier to interpret. A raw CSV can show every observation, but it does not immediately answer whether today's price is close to the historical low, whether a discount is unusually large, or whether the product has been stable for weeks. Matplotlib and pandas are enough for a basic history chart without adding a dashboard framework. The same dataframe can calculate the minimum, maximum, average, and current position before any visualization is drawn.
import pandas as pd
import matplotlib.pyplot as plt


history = pd.read_csv(
    "price_history.csv",
    parse_dates=["timestamp"],
)

history["price"] = pd.to_numeric(
    history["price"],
    errors="coerce",
)

history = history.dropna(subset=["price"])
history = history.sort_values("timestamp")

current_price = history.iloc[-1]["price"]
lowest_price = history["price"].min()
highest_price = history["price"].max()
average_price = history["price"].mean()
is_lowest = current_price == lowest_price

print(f"Current: {current_price:.2f}")
print(f"Lowest: {lowest_price:.2f}")
print(f"Highest: {highest_price:.2f}")
print(f"Average: {average_price:.2f}")
print(f"At historical low: {is_lowest}")

history.plot(
    x="timestamp",
    y="price",
    legend=False,
)

plt.title("Amazon Price History")
plt.xlabel("Date")
plt.ylabel("Price")
plt.tight_layout()
plt.show()
These statistics also make a better alert system possible. Instead of sending a message for every small decrease, the script could alert only when the current price reaches the lowest observed value or drops a specified percentage below the rolling 30-day average. That kind of logic is where building a price tracker becomes more interesting than simply scraping a number. It is also the point where data quality becomes critical, because one incorrectly extracted price can distort every historical metric that follows.

When a DIY Script Stops Making Sense

For one to five products, a DIY tracker can be extremely economical. The direct infrastructure cost may be close to zero if the script runs on an existing computer, and the entire dataset fits comfortably in a CSV file. Custom logic is easy because there is only one codebase and one user deciding how alerts should behave. At that scale, building the tracker can be more valuable than buying software because it provides complete control and teaches how the underlying monitoring workflow actually works.

Scaling changes the economics because each tracked product multiplies operations rather than just adding one database row. With three checks per day, 5 products generate about 450 scheduled page checks per 30-day month, 20 products generate 1,800, and 100 products generate 9,000. Those request counts are not inherently enormous, but they create more opportunities for layout differences, unavailable offers, locale-specific output, retries, missed jobs, and selectors that silently return nothing. Monitoring reliability therefore becomes a maintenance problem long before storage capacity becomes a problem.

A practical planning range for the build-vs-buy decision is roughly 20–100 actively monitored products, but this should be treated as a heuristic rather than an industry law. A developer tracking 100 stable URLs once per day may happily maintain the system for years, while a retailer monitoring 20 volatile Amazon offers across several countries may hit operational complexity much earlier. Frequency, number of marketplaces, required uptime, offer-level matching, geographic variation, and the value of a missed price change matter more than the SKU count alone. The numerical range is useful because it forces a cost discussion, not because product number 21 or 101 automatically changes the correct architecture.

Consider a simple total-cost-of-ownership scenario. If maintaining selectors, investigating failures, checking data quality, and keeping scheduling infrastructure alive takes three hours per month, an internal technical cost of $40 per hour already represents $120 per month in labor before hosting, regional data collection, monitoring, or alert infrastructure is counted. Five maintenance hours raise that implied cost to $200, while a major Amazon markup change can create an additional one-off debugging task. The DIY solution can still be the right choice if its custom logic creates enough value, but “the script is free” stops being an accurate description once maintenance time becomes recurring work.

There is another hidden cost: silent failure. A script that crashes loudly can be repaired, but a scraper that continues running while extracting the wrong seller price, the wrong currency, or no observations at all may corrupt the dataset for days before anyone notices. Production monitoring therefore needs health checks, validation rules, failure-rate reporting, selector diagnostics, and ideally a secondary way to verify suspicious values. At that point, the project is evolving from a Python script into a small data-collection system.

This is where a managed platform starts solving a different problem rather than merely replacing the code above. Priceva's Amazon Price Tracker is designed for retailers and marketplace sellers that need catalog-scale competitor monitoring rather than a personal price alert, with price and availability monitoring, historical analysis, alerts, exports, marketplace coverage, and repricing workflows. Priceva currently provides a free entry tier for up to 20 tracked products and paid plans that scale check volume and product coverage, which also makes the 20–100-product range a useful point for comparing the real monthly cost of internal maintenance against a managed workflow.

Common Mistakes and Troubleshooting

Most broken trackers fail for predictable reasons rather than because Python suddenly stopped working. The first diagnostic question should always be whether the saved HTML still contains the product information the parser expects. If the response is correct but extraction fails, the problem is probably a selector or locale assumption; if the response itself is a challenge page or an error, the network and access layer should be investigated first. Keeping those two failure classes separate prevents hours of changing Beautiful Soup code when the parser never received a real product page.

  1. Relying on one old selector. Amazon page structure varies by product and evolves over time, so a selector such as the retired priceblock_ourprice is not a durable foundation. Use a short, scoped fallback chain, record which selector matched, and inspect the saved HTML whenever all selectors begin returning None.
  2. Hardcoding credentials. Gmail App Passwords, API credentials, database passwords, and webhook secrets do not belong inside tracker.py. Environment variables or a proper secret-management system reduce the chance that a public repository or shared ZIP file accidentally exposes live credentials.
  3. Letting one request failure stop everything. Network timeouts, 429, 503, unavailable products, and changed markup are normal operational events for any remote-data workflow. Catch failures per product, log them with timestamps, apply bounded retries where appropriate, and allow the remaining scheduled checks to continue.
  4. Checking far more often than the use case requires. A loop running every minute produces 720 times as many checks as a 12-hour schedule while offering little value for a product whose price changes once every few days. Start around 6–12 hours, measure how often meaningful changes are actually observed, and shorten the interval only when the business case justifies it.

Conclusion

A working Amazon price tracker needs more than one Beautiful Soup selector. The complete workflow combines resilient price extraction, exact monetary parsing, timestamped history, threshold alerts, scheduling, retry logic, and monitoring for silent failures. Starting with one or a few ASINs keeps the project easy to understand and makes each layer straightforward to test before scale introduces operational complexity. When maintaining selectors, access methods, regional variations, and monitoring reliability begins taking more time than analyzing the pricing data, a managed alternative becomes economically sensible; Priceva's Amazon Price Tracker applies the same monitoring principle across larger catalogs, competitors, and pricing workflows without requiring a retailer to maintain its own scraping stack.

Amazon Price Tracker Python FAQ

Is it legal to scrape Amazon for price data?

There is no universal yes-or-no answer because legality depends on jurisdiction, the data being collected, how access occurs, and how the resulting data is used. Separately from applicable law, Amazon's current terms restrict automated data extraction and collection of product listings and prices in several services. A production project should review both the relevant Amazon terms and local legal requirements rather than assuming that publicly visible automatically means unrestricted for automated reuse. Eligible use cases may also be able to use Amazon's official Creators API.

Why does my Amazon scraper return None for the price?

The most common cause is selector drift or a different page layout. Amazon product pages can place the main offer under different containers, which is why a fallback chain around scoped a-offscreen elements is more reliable than one old ID. The response should also be inspected to make sure it is actually a product page rather than a CAPTCHA, error page, login-dependent view, or localized layout. Saving a failed HTML response during debugging usually reveals the problem faster than blindly adding selectors.

How often should a Python Amazon price tracker check prices?

For ordinary products, every 6–12 hours is a practical starting point. That provides enough observations to detect meaningful daily movement without generating large volumes of repetitive requests. Shorter intervals can make sense during genuinely time-sensitive events, but monitoring frequency should be increased only when the value of detecting a change sooner justifies the additional operational load. The site's applicable access rules and rate limits should always take priority over a desired interval.

Do I need proxies to track Amazon prices?

Not necessarily for a small, permitted experiment monitoring a few products at a conservative frequency. Proxy infrastructure becomes more relevant when an approved use case requires regional observations, distributed collection, or a much larger monitoring workload. Residential and datacenter proxies have different cost, locality, and operational characteristics, but neither is a substitute for permission to access or collect data. A CAPTCHA or access restriction should not be treated as an invitation to circumvent the control.

Can the same Python tracker monitor Amazon.co.uk, Amazon.de, and other marketplaces?

Yes, the underlying architecture can support multiple Amazon marketplaces, but simply changing .com to another domain is not the entire job. Currency, decimal formatting, language, offer structure, geographic personalization, and page markup can differ, so the domain, locale headers, parser, and stored currency all need to be handled explicitly. Amazon's official Creators API likewise supports marketplace-specific requests across numerous regional stores through its marketplace configuration. Each regional store's applicable terms should also be reviewed independently.

When does a managed price tracking tool make more sense than a custom script?

A useful planning range is around 20–100 actively monitored products, although the right point depends on frequency, marketplaces, reliability requirements, and internal developer cost rather than SKU count alone. Below that range, a DIY build often provides excellent flexibility at minimal infrastructure cost. As monitoring expands, recurring work shifts toward selector maintenance, failed requests, data validation, alert reliability, and regional differences. When that maintenance cost exceeds the value of owning the custom stack, a catalog-scale platform such as Priceva becomes the more practical option.

About the author
Daniel Reeves
Software Engineer & Ecommerce Technology Writer at Priceva
Daniel Reeves is a software engineer and technical writer specializing in ecommerce infrastructure, pricing APIs, and retail data systems. With a background in backend development and 8+ years working with price intelligence platforms, Daniel covers topics at the intersection of technology and retail operations at Priceva.
More to explore
✓ Unlimited free trial ✓ No credit card required ✓ Support 24/7 ✓ Cancel anytime
Monitor prices, stock & MAP violations across 10,000+ stores — starting today
BOOST YOUR REVENUE
Start Your Free Trial