Competitor price monitoring often starts after a lost deal. A competitor cut a price three weeks ago, and sales hears about it from a prospect.
The right setup depends on who you are:
- A handful of URLs, no developer: Visualping, Distill or changedetection.io.
- Thousands of SKUs, product matching, repricing or MAP: Prisync or Price2Spy.
- Prices in your own database, with your own rules, across many sites: a script. This post builds one.
I wrote a single-file Python price tracker plus 49 tests and ran it in Docker on November 21, 2026: on two scrape-practice sites, on 7 real product pages and on 3 SaaS pricing pages. I re-ran the JavaScript test on November 22. Every number below comes from those runs or a linked pricing page. I run WebCrawlerAPI, so the fetch layer is ours, but any scraping API fits the same scrape() function.
How do you monitor competitor prices automatically without an enterprise tool?
Keep a watch list of competitor product URLs and fetch each page once or twice a day with a cron job and a scraping API that runs JavaScript (plain requests works for simple, static shops). Read the price from the page's structured data first (JSON-LD or microdata was there on 6 of 7 real store pages I tested), fall back to a site parser or an LLM extraction schema, and normalize it to a decimal amount plus a currency code. Store every reading in SQLite and alert only when the same new price shows up on two runs in a row and moves past a threshold such as $1 and 2%; failed fetches and missing prices go to a human, never into a price-drop alert.
To track competitor prices for 100 products daily this way, the fetch bill is about $6 a month on WebCrawlerAPI's Pay as you go plan. For a handful of pages and no developer, a free change monitor such as Visualping, Distill or changedetection.io is less work.
Competitor price monitoring software vs a DIY script
I read each vendor's pricing page on November 21, 2026. Prices vary by region and tax.
| Option | Good for | Entry price (as of November 2026) | Limits that matter | Pick it over a script when |
|---|---|---|---|---|
| DIY script + scraping API | Developers who want prices in their own database | $0/month + $0.002 per page on WebCrawlerAPI Pay as you go (pricing) | You maintain the parsers and alert rules yourself | You have a developer and want prices, history and custom rules in your own database |
| Visualping | Non-developers watching pages for visual or text changes | Free: 150 checks/month, 5 pages, 60 min interval. Personal 1K: $14/month for 10 pages | 200 pages needs Business 20K at $140/month. API calls use the same check quota | You watch about 10 pages or fewer and want a UI with email alerts |
| Distill.io | Individuals, monitors that run in your browser | Free: 25 monitors (5 in cloud), 6 h cloud interval. Starter: $15/month | Professional is $35/month for 150 monitors and 100,000 cloud checks | You want browser-based checks, or fewer than 150 pages |
| changedetection.io | Change detection with restock and price alerts | Hosted: $8.99/month with 5,000 page watches. Open source, self-host with Docker (GitHub) | Self-hosting means you run and update the server | You need "tell me when this page changes" and its UI is enough |
| Prisync | E-commerce teams with a real catalog | URL-based Professional: 99/month for up to 100 products, 3 price updates a day (no currency on plan prices; add-ons are priced in $). 14-day trial | API access starts on Premium (199/month, 1,000 products) and costs 20% extra | You need repricing, MAP monitoring or someone to match products for you |
| Price2Spy | Retailers and brands, marketplaces, MAP | Starter and Basic: not listed publicly. Premium: price on request. Free trial | Starter has daily alerts and up to 10 competitors. API access is on Premium | You need marketplace monitoring, MAP, repricing or a product matching service |
Notes on that table:
- Marketplaces like Amazon and MAP enforcement are tool territory. This script targets brand sites and online stores. I didn't test it on any marketplace.
- Enterprise pricing platforms such as Competera, Wiser and Omnia Retail add price optimization or dynamic pricing on top of monitoring.
How the pipeline works
One run goes through eight steps: watch list, schedule, fetch, extract, normalize, store, diff, alert. A failed fetch or a missing price never counts as a price change.

This is website change detection in Python, narrowed to one field. Instead of hashing the whole page and alerting on any diff (the approach in recrawling only changed docs pages), the script extracts the price and diffs that. Most of the code fights false alarms, because a noisy alert channel gets muted fast.
What to track before you write code
- Which products first. Your top sellers against the two or three competitors sales names most. Add more once you trust the alerts.
- Product matching. Each SKU needs the right competitor URL, often per variant. That manual work is the real setup cost, and a fair reason to pay Prisync (a "competitor matching service") or Price2Spy (product matching).
- Shelf price and list price. Store both and compare what the customer pays. My script only gets the list price from the schema fallback.
- Stock. Out of stock is its own event, never a price.
- Shipping, coupons, bundles, member prices. The script reads only the shelf price, so track them as separate fields if they matter.
- Variants. One row per variant URL. The script takes the first offer on the page.
Step 0: Build the watch list
The watch list is a CSV file. Here are three of my seven rows, including one URL that doesn't exist on purpose:
your_sku,competitor,url,expected_currency,decimal_sep,extractor BOOK-001,books.toscrape,https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html,GBP,.,auto LAPTOP-060,webscraper.io,https://webscraper.io/test-sites/e-commerce/allinone/product/60,USD,.,auto BOOK-404,books.toscrape,https://books.toscrape.com/catalogue/this-book-does-not-exist_0/index.html,GBP,.,auto
expected_currency and decimal_sep are hints for the price parser (Step 3). Where all variants share one page, record the lowest "from" price and flag it.
A category page showing 30 prices covers 30 products in one request. Check robots.txt for listings: the webscraper.io test shop disallows /test-sites/pagination/.
Step 1: Fetch the page
Only this function talks to WebCrawlerAPI:
API = "https://api.webcrawlerapi.com/v2/scrape"
# ...
REQUEST_FAILED = "request_failed" # local status, not a WebCrawlerAPI error code
RETRY_ONCE = {"timeout_error", "webpage_non_success", "internal_error", REQUEST_FAILED}
STOP_RUN = {"insufficient_balance"} # documented account-level code: no point checking more URLs
# ...
def scrape(url, **params):
"""POST /v2/scrape. Failures come back as HTTP 200 with success=false and an error_code."""
body = {"url": url, "output_formats": ["html"], "max_age": 0, # max_age 0: never a cached price
"respect_robots_txt": True, **params}
headers = {"Authorization": f"Bearer {os.environ['WEBCRAWLERAPI_KEY']}"}
for attempt in range(2):
try:
r = requests.post(API, json=body, headers=headers, timeout=180)
if r.status_code in (401, 402): # bad key or no balance: stop the whole run
r.raise_for_status()
data = r.json()
except requests.HTTPError:
raise
except (requests.RequestException, ValueError): # network error, timeout or a non-JSON reply
data = {"success": False, "error_code": REQUEST_FAILED}
if data.get("error_code") in STOP_RUN:
raise SystemExit(f"stopping the run: {data['error_code']}")
if data.get("success") or data.get("error_code") not in RETRY_ONCE or attempt:
return data
time.sleep(10) # one retry for transient failures, the next scheduled run does the rest
max_age: 0 is the most important line here. WebCrawlerAPI caches scrape results for 7 days by default (caching docs), so without it you might compare against a week-old price. Every plain scrape in my runs came back X-Cache: MISS.
The script asks for html because structured data lives in <script> tags and attributes, which markdown drops. It branches on error_code, never on the error message. A blocked fetch comes back as website_access_denied (a 403), timeout_error or webpage_non_success (error codes) and gets recorded without a price alert. None of my test sites blocked the fetch, so I have no data on how often blocking happens.
A network error or a non-JSON reply becomes a failed fetch under request_failed, a local label, so one bad URL doesn't kill the run. Only insufficient_balance stops the run, since every other URL would fail too.
No country parameter is documented for scrape, and a shop may switch currency by visitor location, so every reading stores its currency. For other APIs, see best web scraping APIs.
JS-heavy shops: when the price isn't in the HTML
Some shops fill in prices with JavaScript after the page loads. A plain requests.get only gets the HTML from before that, so the price isn't there.
/v2/scrape opens the page in a headless browser by default, so the JavaScript runs before you get the HTML back. There's no extra parameter to turn on. The same scrape() call works:
data = scrape(url, output_formats=["html", "markdown"]) # same body as above: max_age 0, robots.txt respected
I re-ran this test on November 22, 2026, in Docker, one request per page, max_age: 0:
| Page | Plain requests.get | /v2/scrape |
|---|---|---|
| React demo shop, products loaded by JavaScript | 2,058 chars of HTML, 0 prices | 13,225 chars of HTML, all 16 products with prices ($10.90, $13.25, ...), 4.8 s |
| quotes.toscrape.com /js/, quotes written by JavaScript | 0 quotes | 10 quotes, 4.9 s |
| quotes.toscrape.com /js-delayed/, quotes appear after a 10-second timer | 0 quotes | 0 quotes, the same HTML as the plain request, 19.8 s |
The third row is the catch. The browser doesn't wait forever. Its first try found an empty page, the API retried, and the retry returned the HTML without the JavaScript content. It still came back as success: true. Store C in the real-store test below went the same way: the browser try timed out, and the HTML that came back had no visible price.
How to handle it:
- Don't trust success: true alone. The page loads, but no extractor finds a price. Record an extraction failure, never 0 or a drop.
- Check the first HTML anyway. On Store C, a real Shopify store, the visible price was missing, but the JSON-LD had it.
- Find the JSON endpoint. If the browser's Network tab shows the page fetching prices from a public JSON endpoint, call that instead.
- Run your own browser for slow pages. If the price shows up many seconds after load, Playwright with an explicit wait for the price element is more work to host, but you control the wait.
More on how rendering works: JavaScript rendering in web crawling.
Step 2: Extract the price
The script tries three extractors in order and stops at the first price.
Option A: structured data in the HTML (try this first)
Shops often publish the price for search engines: a schema.org Offer in JSON-LD, microdata attributes (itemprop="price") or product:price:amount meta tags. This reader handles all of them:
def from_structured(scan):
"""schema.org Offer in JSON-LD, then microdata (itemprop), then product:price meta tags."""
for blob in scan.ld:
try:
nodes = list(ld_nodes(json.loads(blob)))
except ValueError:
continue
for n in nodes:
if n.get("@type") in ("Offer", "AggregateOffer") and (n.get("price") or n.get("lowPrice")):
return {"price_text": str(n.get("price") or n.get("lowPrice")), "currency": n.get("priceCurrency"),
"in_stock": stock(n.get("availability")), "extractor": "json-ld"}
if scan.props.get("price"):
return {"price_text": scan.props["price"], "currency": scan.props.get("priceCurrency"),
"in_stock": stock(scan.props.get("availability")), "extractor": "microdata"}
if scan.meta.get("product:price:amount"):
return {"price_text": scan.meta["product:price:amount"], "currency": scan.meta.get("product:price:currency"),
"in_stock": None, "extractor": "meta"}
The practice sites had JSON-LD on 0 of 8 pages, so a hand-written test fixture covers that path (JSON-LD 79.00 EUR beats a meta tag's 89.00 EUR). scan comes from Python's built-in HTMLParser, keeping one dependency; for alternatives, see Python HTML parsers compared.
Option B: a site parser on the HTML
For pages without structured data, a small dict maps each domain to the CSS class of its price and stock elements.
# Site parsers for pages without structured data: CSS class of the price and of the stock element.
SITE_PARSERS = {
"books.toscrape.com": {"price": "price_color", "stock": "availability"},
"webscraper.io": {"price": "price", "stock": None}, # product pages show no stock status
}
Site parsers are free and fast, but a redesign breaks them silently. Step 5 turns that into an "extractor broken" alert.
Option C: prompt + response_schema as a fallback
With the --schema flag, the script asks the API's LLM to read the page when both options above come back empty:
SCHEMA = {"type": "object", "additionalProperties": False,
"required": ["price_text", "list_price_text", "currency", "in_stock"],
"properties": {"price_text": {"type": ["string", "null"]}, "list_price_text": {"type": ["string", "null"]},
"currency": {"type": ["string", "null"]}, "in_stock": {"type": ["boolean", "null"]}}}
PROMPT = ("Main product on this page: price_text = the current price exactly as shown, with its currency symbol; "
"list_price_text = the crossed-out original price if one is shown, else null; currency = ISO 4217 code; "
"in_stock = true/false only if the page states it, else null. If no price is shown, price_text = null.")
def extract_with_schema(url):
"""Fallback: the API's LLM reads the page. Billed per page plus tokens. Returns (found, raw response)."""
data = scrape(url, output_formats=["markdown"], prompt=PROMPT, response_schema=SCHEMA)
sd = data.get("structured_data") or {}
return ({**sd, "extractor": "schema"} if sd.get("price_text") else None), data
The schema asks for the price as text, and the same parse_price from Step 3 turns it into a number, so you keep the raw string. Every field is required with a null option and additionalProperties is false, as the structured outputs docs recommend.
With prompt, the response holds structured_data instead of HTML. Keep max_age: 0, since the cache key includes the prompt. On long pages, clean_selectors helps you stay under the context limit (llm_max_context_length_error). The fallback is a second request after a successful HTML fetch.
Cost and speed of each option
On the 8 practice product pages plus the missing URL, single run, max_age: 0 everywhere, medians only:
| Option | Exact price matches | Missing URL | Median latency | Cost per 1,000 checks (Pay as you go) | Maintenance |
|---|---|---|---|---|---|
| A/B: one request (html + markdown), structured data, else site parser | 8/8 | host_returned_error, no price | 3.4 s | $2.00 | A parser per site without structured data |
| C: separate request with prompt + response_schema | 8/8 | no price | 12.4 s | $2.00 for pages + tokens. Docs guide: ~$0.004-0.005 per simple page, so about $6.00-$7.00 total. Estimate, not measured | No parser. Costs tokens, slower |
The A/B request asked for html + markdown; the script asks for html only. The 8/8 is circular (I wrote the parsers against these pages), so read the table for cost and latency. A fallback check costs both rows, about $8-9 per 1,000. No response carried a cost field, so tokens follow the pricing docs guide.
How it did on 7 real stores
To test the extractor order on real shops, I ran the unchanged fetch and extract code once on 7 public product pages (anonymized; robots.txt allowed every path):
| Store | Platform | Extractor that hit | Result |
|---|---|---|---|
| A | Shopify | none | URL served a category page: extractor_broken |
| B | Shopify | JSON-LD | 19.99 USD, matches the page |
| C | Shopify | JSON-LD | 61.6 USD, out of stock: out_of_stock |
| D | WooCommerce | none | served a sibling product; its price sits in priceSpecification: extractor_broken |
| E | WooCommerce | JSON-LD | 12.99 USD, matches the page |
| F | Custom (UK) | microdata | 267 GBP, matches the page |
| G | Custom (US) | JSON-LD | 49 USD, matches the page |
All 7 fetched with no error codes. Structured data was on 6 of 7 pages, and 4 of 4 checkable prices matched the page (C's visible price wasn't in the returned HTML, see JS-heavy shops above). Neither miss produced a wrong price. Both ended as extractor_broken for a human. Median latency was 9.7 s (5.0-19.2 s). It's one snapshot of 7 hand-picked pages, none heavily bot-protected.
Two gaps showed up:
- Redirected URLs. The /v2/scrape response has no final-URL field, so the script can't tell that A and D served another page (D's canonical link names a sibling product). Comparing the canonical URL with the watch-list URL would catch it. My script doesn't do that yet.
- priceSpecification. Store D nests the price at offers.priceSpecification.price, which from_structured doesn't read. If your targets use that shape, read it too.
My rule: structured data first, site parser second, schema fallback only when both find nothing.
Step 3: Normalize prices before you compare anything
parse_price turns a price string into a Decimal plus a currency code, and returns None when there is no price:
def parse_price(text, decimal_sep=None, currency=None):
"""'£51.77' -> Price(Decimal('51.77'), 'GBP'). 'Contact us', 'Out of stock' or '' -> None, never 0."""
if not text or NO_PRICE.search(text):
return None
nums = [to_decimal(m.group(), decimal_sep) for m in NUM.finditer(text)]
if not nums:
return None
code = next((c for c in sorted(CODES) if re.search(rf"\b{c}\b", text)), None)
sym = next((s for s in SYMBOLS if s in text), None)
cur = code or (currency if sym == "$" and currency in DOLLARS else SYMBOLS.get(sym)) or currency
if re.search(r"\b(from|starting at|ab)\b", text, re.I):
return Price(min(nums), cur, "from")
if len(nums) > 1 and re.search(r"\d\s*(-|–|to)\s*\D?\s*\d", text):
return Price(min(nums), cur, "range")
unit = re.search(r"(?:/|\bper\s+)\s*([a-z]{1,5})\b", text, re.I)
return Price(nums[0], cur, f"per {unit.group(1).lower()}" if unit else None)
Each case below is a passing unit test in my test suite:
- Symbols and codes: £51.77 gives 51.77 GBP; 1,299.00 USD and EUR 12,50 work too.
- Decimals: $299 (webscraper.io listing) and $1143.4 (a webscraper.io product page).
- Locale separators: 1.299,00 €, 1 299,00 € with a non-breaking space, CHF 1'299.50.
- Ambiguous strings: 1.299 is 1,299 in Germany and 1.299 in the US. The watch list's decimal_sep settles it; without it, the parser guesses thousands.
- Ambiguous $: $19.99 with a CAD hint is stored as CAD.
- From prices, ranges, units: From $19/mo gives 19 flagged "from", $10 - $20 gives 10 flagged "range", $4.99/lb is flagged "per lb".
- No price: "Contact us", "Call for price", "Out of stock", "Sold out", "Free" and an empty string return None. A 0 would look like a 100% drop.
- Floats: a test checks that $0.10 + $0.20 equals exactly 0.30. With floats it doesn't.
Pick one tax basis per site (books.toscrape.com shows excl. and incl. tax rows; the parser reads the headline price). Keep the raw string next to the parsed value so a wrong number is easy to trace (see how to clean and validate scraped data).
Step 4: Store every reading in SQLite
One table logs every attempt. The other holds the state the diff works on:
DDL = """
CREATE TABLE IF NOT EXISTS observations (id INTEGER PRIMARY KEY, url TEXT, fetched_at TEXT, ok INTEGER,
error_code TEXT, raw_price_text TEXT, price TEXT, currency TEXT, list_price TEXT, in_stock INTEGER, extractor TEXT);
CREATE TABLE IF NOT EXISTS products (url TEXT PRIMARY KEY, confirmed_price TEXT, confirmed_currency TEXT,
pending_price TEXT, pending_count INTEGER DEFAULT 0, error_streak INTEGER DEFAULT 0, last_alert_at TEXT,
pending_currency TEXT);
""" # prices are TEXT, so Decimal('51.77') comes back exactly
products holds the confirmed price and currency, a pending price and currency waiting for a second sighting, an error streak and the last alert time. observations keeps failures too, so one query gives a product's history:
SELECT fetched_at, price, currency, extractor, error_code FROM observations
WHERE url = 'https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html'
ORDER BY fetched_at;
On my recorded database it returns the three runs:
2026-11-21T15:43:53+00:00|51.77|GBP|site:price_color| 2026-11-21T15:44:20+00:00|51.77|GBP|site:price_color| 2026-11-21T15:44:36+00:00|51.77|GBP|site:price_color|
The live price never moved: the alert later in this post came from a hand edit to products.
Step 5: Send price change alerts only for real changes
The rules
RULES = {"min_abs": Decimal("1.00"), "min_pct": Decimal("2"), "confirm_runs": 2, "cooldown_hours": 24}
# ...
GONE_AFTER = 3 # failed fetches in a row, the latest a host_returned_error, before a listing counts as gone
- Compare with the confirmed price. Against the previous row, a flip-flopping price alerts on every run.
- Threshold on both: the move must be at least 1.00 in the product's currency ($1, £1) and at least 2%. A 0.50 move on a $296 laptop stays quiet. min_abs is one global value in currency units, so for JPY or INR make it a dict keyed by currency code.
- Confirm twice: alert only when the same new price shows up on two runs in a row. A/B tests and one-off glitches drop out.
- Cooldown: at most one alert per product per 24 hours (unit-tested; my demo runs were seconds apart).
- Currency changed: it goes through confirm-twice like a price, then fires one review_currency event and becomes the new baseline. Otherwise 54.99 GBP to 64.99 EUR would read as an 18% increase.
All of it lives in one pure function:
def should_alert(state, r, rules=RULES, now=None):
"""Pure function: (product state, new reading) -> (event, detail, new state)."""
now, s = now or datetime.now(timezone.utc), dict(state)
if not r.ok: # a failed fetch is never a price change
s["error_streak"] = (s.get("error_streak") or 0) + 1
gone = r.error_code == "host_returned_error" and s["error_streak"] >= GONE_AFTER
return ("listing_gone" if gone else "fetch_failed"), f"{r.error_code} ({s['error_streak']}x in a row)", s
s["error_streak"] = 0
if r.in_stock is False:
return "out_of_stock", "page says out of stock", s
if r.price is None: # page loaded, parser found nothing: a redesign, not a price drop
return "extractor_broken", "page loaded, no price found", s
if s.get("confirmed_price") is None:
s.update(confirmed_price=r.price, confirmed_currency=r.currency)
return "seeded", f"{r.price} {r.currency}", s
old = Decimal(s["confirmed_price"])
new_currency = r.currency != s.get("confirmed_currency") # 54.99 GBP -> 64.99 EUR is not +18%
delta = r.price - old
pct = delta / old * 100
if not new_currency and (abs(delta) < rules["min_abs"] or abs(pct) < rules["min_pct"]):
s.update(pending_price=None, pending_currency=None, pending_count=0)
return ("unchanged" if delta == 0 else "below_threshold"), f"{old} -> {r.price} ({pct:+.1f}%)", s
pending = s.get("pending_price") is not None and (Decimal(s["pending_price"]), s.get("pending_currency"))
same = pending == (r.price, r.currency) # a candidate is a price AND a currency
s.update(pending_price=r.price, pending_currency=r.currency,
pending_count=(s.get("pending_count") or 0) + 1 if same else 1)
move = (f"{s.get('confirmed_currency')} -> {r.currency} ({old} -> {r.price})" if new_currency
else f"{old} -> {r.price} {r.currency} ({pct:+.1f}%)")
detail = f"{move}, seen {s['pending_count']}/{rules['confirm_runs']} runs"
if s["pending_count"] < rules["confirm_runs"]:
return "pending", detail, s
if new_currency: # confirmed twice like a price, then fired ONCE: the new currency and price become the
# baseline, so the next run compares EUR with EUR instead of re-firing review_currency on every run
s.update(confirmed_price=r.price, confirmed_currency=r.currency,
pending_price=None, pending_currency=None, pending_count=0)
return "review_currency", detail, s
last = s.get("last_alert_at")
if last and now - datetime.fromisoformat(last) < timedelta(hours=rules["cooldown_hours"]):
return "cooldown", detail, s
s.update(confirmed_price=r.price, pending_price=None, pending_currency=None, pending_count=0,
last_alert_at=now.isoformat())
return "alert", detail, s
No database, no network, so every rule is cheap to test. In the flicker test, a candidate price changes before it's confirmed, then returns to normal, and no alert fires.
Failed fetches and missing prices
Errors follow the documented codes. A 403 comes back as website_access_denied, and other non-2xx responses, 404 included, as host_returned_error. timeout_error, webpage_non_success, internal_error and the local request_failed get one retry after 10 seconds. For more, use exponential backoff. blocked_by_robots_txt means the shop disallows that path: drop it from the watch list.
A product becomes listing_gone after 3 failed fetches in a row when the latest one is a host_returned_error. One 404 alone can be a deploy hiccup.
A page with no price gives extractor_broken. Many of those from one domain in one run mean a redesign or a block.
What the alert says
Each run prints one grouped report, alerts first, digest last. With ALERT_WEBHOOK_URL set (a Slack-style incoming webhook), urgent events also go there. The header line ("7 URLs, 6 fetched OK, 1 failed") doubles as a heartbeat.
Route alerts to whoever owns pricing (or sales, for SaaS), with the product link. The script never changes your prices. That's a repricer's job, and on marketplaces you'll want one.
Step 6: Run it on a schedule
Once or twice a day is enough for most competitor pricing:
15 7 * * * cd /srv/pricemon && docker run --rm --env-file /etc/pricemon.env -v "$PWD":/work pricemon-py python price_monitor.py
Cron doesn't load your shell profile, so keep the key in an env file only you can read (chmod 600), outside the mounted folder and out of git.
GitHub Actions works with a schedule trigger, but the runner is thrown away after each run, so persist the SQLite file (commit it, cache it, or use Postgres). Scheduled runs can be delayed or dropped, and public repos disable them after 60 days without activity (GitHub docs).
For hundreds of URLs, use batch scrape (batch docs):
- POST /v2/batch/scrape takes urls, max_age: 0 and max_concurrency (Pay as you go allows 5 parallel requests, rate limits), and returns a batch id at once.
- Poll GET /v2/batch/scrape/:id or set webhook_url.
- Request ["html"] and read each item's html_url.
- Batch size is capped by your plan's job items limit (100 during trial); no prompt or response_schema.
See also scraping multiple URLs.
WebCrawlerAPI feeds are the managed alternative: a scheduled recrawl with a webhook on changes, paused after 3 consecutive errors. Any content change can trigger it (a new review counts), so you still extract and diff the price.
Monitoring competitor SaaS pricing pages
For SaaS pricing pages I wrote a separate 75-line saas_plans.py. It imports scrape() and parse_price() from price_monitor.py and asks the API's LLM for every plan on the page:
PLANS_SCHEMA = {
"type": "object", "additionalProperties": False, "required": ["plans"],
"properties": {"plans": {"type": "array", "items": {
"type": "object", "additionalProperties": False,
"required": ["name", "price_text", "billing_period", "per_seat", "limits"],
"properties": {"name": {"type": "string"}, "price_text": {"type": ["string", "null"]},
"billing_period": {"type": ["string", "null"]}, "per_seat": {"type": ["boolean", "null"]},
"limits": {"type": "array", "items": {"type": "string"}}}}}}}
PLANS_PROMPT = (
"List every pricing plan on this page. If the page shows both monthly and annual prices, return one entry per "
"plan and billing period. name = plan name as shown; price_text = the price exactly as shown, with currency "
"symbol and unit, or null for 'Contact sales' / custom pricing; billing_period = 'month', 'year', 'one-time' or "
"'usage' (pay as you go), null if the page does not say; per_seat = true if priced per user or seat, false if "
"not, null if unclear; limits = up to 5 key limits as short strings, e.g. '10,000 pages/month'. "
"Use only what the page shows.")
def get_plans(url):
"""One /v2/scrape request with a prompt (billed per page plus tokens). Returns (plans or None, raw response)."""
data = scrape(url, output_formats=["markdown"], prompt=PLANS_PROMPT, response_schema=PLANS_SCHEMA)
return (data.get("structured_data") or {}).get("plans") if data.get("success") else None, data
I ran it once on each of three pricing pages: our own webcrawlerapi.com/pricing, Supabase and Netlify.
- 11 plans, 0 wrong prices. "Contact us" plans came back as null, not 0.
- Two misreads. One plan sold "for 1 member" got per_seat: true. A plan whose card says "Everything in the Pro Plan, plus:" came back with Pro's limits instead of its own features, so a features change there wouldn't show in the diff.
- No page had annual prices in the fetched content, so monthly vs annual is untested. With a JavaScript toggle, check the fetched markdown first.
- The schema request took 18-22 s per page, against 3-4 s for plain markdown.
It saves the last plan list per URL to a JSON file and diffs each run against it, keyed by plan name and billing period:
def diff_plans(old, new):
"""Two plan lists -> sorted list of changes: added/removed plans, changed price, seat model or limits."""
key = lambda p: (p["name"].strip().lower(), p.get("billing_period"))
price = lambda p: (pp := parse_price(p.get("price_text"))) and (pp.amount, pp.currency) # "$20/mo" == "$20 / mo"
before, after = {key(p): p for p in old}, {key(p): p for p in new}
changes = [f"added {n} ({b}): {after[n, b]['price_text']}" for n, b in after.keys() - before.keys()]
changes += [f"removed {n} ({b})" for n, b in before.keys() - after.keys()]
for k in before.keys() & after.keys():
o, n = before[k], after[k]
if price(o) != price(n):
changes.append(f"price {k[0]} ({k[1]}): {o['price_text']} -> {n['price_text']}")
if o.get("per_seat") != n.get("per_seat"):
changes.append(f"per_seat {k[0]} ({k[1]}): {o.get('per_seat')} -> {n.get('per_seat')}")
if sorted(o.get("limits") or []) != sorted(n.get("limits") or []):
changes.append(f"limits {k[0]} ({k[1]}): {o.get('limits')} -> {n.get('limits')}")
return sorted(changes)
diff_plans compares parsed amounts, so "$99/month" vs "$99 / month" is no change. A renamed plan shows up as removed plus added. Limits stay plain text and the model may reword them, so confirm a limits change on a second run.
This demo output is simulated. Live plans don't change a minute apart, so I edited the stored snapshot by hand: Professional at $89, an extra Starter plan, one Business limit deleted. The live side is the real webcrawlerapi.com/pricing result:
limits business (month): [3 limits] -> [same 3 + 'Charged only for successful requests'] # shortened price professional (month): $89/month -> $99/month removed starter (month)
For the general extraction approach, see how to extract SaaS pricing from any website.
What it costs
Products x checks per day x 30 = pages per month. You pay the higher of the monthly fee and pages x per-page rate, and only successful requests are charged (pricing docs). My 404 came back success: false, so per that rule it shouldn't be billed.
| Plan | Monthly fee | Per page |
|---|---|---|
| Pay as you go | $0 | $0.002 |
| Professional | $99 | $0.0015 |
| Business | $499 | $0.001 |
All cheapest on Pay as you go:
- 50 products, once a day: 1,500 pages, $3.00/month
- 100 products, once a day: 3,000 pages, $6.00/month
- 500 products, twice a day: 30,000 pages, $60.00/month (Professional would be $99)
Pay as you go stays cheapest below 49,500 pages a month ($99 / $0.002). From 49,500 to 66,000 pages, Professional costs a flat $99. Business wins above about 332,700 pages a month.
If all 3,000 monthly checks for 100 products fell back to prompt + response_schema, each would add a second page fee ($0.002) plus ~$0.004-0.005 in tokens (docs guide). My estimate: $18-21 a month on top of the $6 base.
Each competitor price monitoring tool at the same volume, as of November 2026: 100 pages on Visualping needs Business 20K at $140/month, since Personal 10K stops at 40 pages. changedetection.io hosted is $8.99/month, close to the script's fetch bill.
Legal and polite price scraping
Check each site's robots.txt and terms; this isn't legal advice. The script sends respect_robots_txt: true, checks daily, never logs in and collects no personal data. More in is web scraping legal and web scraping ethics.
Run the full script
price_monitor.py is a 341-line price monitoring script: Python 3.12, standard library plus requests. The full listing is at the end of this post, after the FAQ, and the product-page excerpts in Steps 1-5 match it exactly. The plans code (PLANS_SCHEMA, PLANS_PROMPT, get_plans, diff_plans) lives in saas_plans.py.
Sign up and copy your key from the API key section of the dashboard (docs). Save the three-row CSV from Step 0 as urls.csv, with the header your_sku,competitor,url,expected_currency,decimal_sep,extractor. One run on it is two billable pages, $0.004 on Pay as you go.
Build a small image once, then run the monitor:
printf 'FROM python:3.12-slim\nRUN pip install --no-cache-dir requests==2.32.3\nWORKDIR /work\n' \
| docker build -t pricemon-py -
# export WEBCRAWLERAPI_KEY=YOUR_API_KEY first; never commit the key
docker run --rm -e WEBCRAWLERAPI_KEY -v "$PWD":/work pricemon-py \
python price_monitor.py --urls urls.csv --db prices.db
My offline test suite (49 tests on price parsing, structured data, alert rules and failed fetches) passed:

Then I ran the monitor live three times against the practice sites, 27 and 16 seconds apart, through a thin wrapper that only logs requests. Run 1 seeded 6 prices; the missing URL came back as host_returned_error, with no price recorded.
The price changes below are simulated. Practice-site prices never change, so before run 2 I edited the stored confirmed_price in SQLite by hand: BOOK-001 from 51.77 to 54.99 and LAPTOP-060 from 295.99 to 296.49. The live pages kept their real prices, so runs 2 and 3 saw a 5.9% drop on the book and a 0.50 move on the laptop. Run 2:
# NOTE: confirmed_price was edited by hand before this run (SIMULATED change, see simulated_change.sql): # BOOK-001 54.99 (real page price 51.77), LAPTOP-060 296.49 (real page price 295.99). $ python price_monitor.py --urls urls.csv --db data/prices.db Price check 2026-11-21 15:44 UTC: 7 URLs, 6 fetched OK, 1 failed PENDING (waits for a second run) (1) pending BOOK-001 54.99 -> 51.77 GBP (-5.9%), seen 1/2 runs NEEDS A LOOK (1) fetch_failed BOOK-404 host_returned_error (2x in a row) DIGEST (5) unchanged BOOK-002 53.74 -> 53.74 (+0.0%) unchanged BOOK-003 50.10 -> 50.10 (+0.0%) below_threshold LAPTOP-060 296.49 -> 295.99 (-0.2%) unchanged LAPTOP-110 1143.4 -> 1143.4 (+0.0%) unchanged LAPTOP-120 1187.98 -> 1187.98 (+0.0%)
Run 3 saw the same price again, so the confirm-twice rule fired. The missing URL hit its third host_returned_error and became listing_gone:

The laptop stayed in the digest as below_threshold both times: the $1 / 2% rule at work.
Instead of raw requests, you can use the Python SDK (pip install webcrawlerapi): its scrape() method takes one URL, or a list of URLs for a batch.
FAQ
How often should I check competitor prices?
Once a day covers most stores and SaaS pricing pages; twice a day for flash sales. With confirm-twice, daily checks alert one to two days after a change. More in how often to recrawl a website.
How do I stop false price-drop alerts?
Compare against a confirmed price, require at least $1 and 2%, and alert only after two runs see the same new price. Log failed fetches and missing prices as their own events, and send max_age: 0 to skip cached pages.
Python script or changedetection.io: which should I use?
changedetection.io is website change detection with restock and price alerts. If that's enough, use it (self-hosted, or $8.99/month hosted). Write a script for normalized prices from many sites in your own database.
How much does it cost to monitor 100 products daily?
100 products x 30 days = 3,000 pages, or $6.00 a month on WebCrawlerAPI Pay as you go. If every check fell back to the LLM schema, add roughly $18-21 for a second page fee plus tokens (a docs-based estimate).
Is it legal to scrape competitor prices?
It depends on your country and the site's terms; this isn't legal advice. Respect robots.txt, check at most twice a day, skip anything behind a login, and collect no personal data.
Full script: price_monitor.py
#!/usr/bin/env python3
"""Competitor price monitor: watch list -> fetch -> extract -> normalize -> SQLite -> diff -> alert.
WEBCRAWLERAPI_KEY=... python price_monitor.py --urls urls.csv --db prices.db [--schema]
Optional env ALERT_WEBHOOK_URL: Slack-style incoming webhook (a secret: never hardcode or log it).
Python 3.12, stdlib + requests.
"""
import argparse, csv, json, os, re, sqlite3, time
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from html.parser import HTMLParser
from typing import NamedTuple
from urllib.parse import urlparse
import requests
API = "https://api.webcrawlerapi.com/v2/scrape"
RULES = {"min_abs": Decimal("1.00"), "min_pct": Decimal("2"), "confirm_runs": 2, "cooldown_hours": 24}
REQUEST_FAILED = "request_failed" # local status, not a WebCrawlerAPI error code
RETRY_ONCE = {"timeout_error", "webpage_non_success", "internal_error", REQUEST_FAILED}
STOP_RUN = {"insufficient_balance"} # documented account-level code: no point checking more URLs
GONE_AFTER = 3 # failed fetches in a row, the latest a host_returned_error, before a listing counts as gone
# ---------- 1. Fetch ----------
def scrape(url, **params):
"""POST /v2/scrape. Failures come back as HTTP 200 with success=false and an error_code."""
body = {"url": url, "output_formats": ["html"], "max_age": 0, # max_age 0: never a cached price
"respect_robots_txt": True, **params}
headers = {"Authorization": f"Bearer {os.environ['WEBCRAWLERAPI_KEY']}"}
for attempt in range(2):
try:
r = requests.post(API, json=body, headers=headers, timeout=180)
if r.status_code in (401, 402): # bad key or no balance: stop the whole run
r.raise_for_status()
data = r.json()
except requests.HTTPError:
raise
except (requests.RequestException, ValueError): # network error, timeout or a non-JSON reply
data = {"success": False, "error_code": REQUEST_FAILED}
if data.get("error_code") in STOP_RUN:
raise SystemExit(f"stopping the run: {data['error_code']}")
if data.get("success") or data.get("error_code") not in RETRY_ONCE or attempt:
return data
time.sleep(10) # one retry for transient failures, the next scheduled run does the rest
# ---------- 2. Extract ----------
class PageScan(HTMLParser):
"""One pass over the HTML: JSON-LD blocks, microdata props, product:price meta, first text per CSS class."""
def __init__(self, classes=()):
super().__init__()
self.classes, self.ld, self.props, self.meta, self.by_class = set(classes), [], {}, {}, {}
self._open = [] # [tag, key, text parts, nested same-tag depth]
def handle_starttag(self, tag, attrs):
a = dict(attrs)
for o in self._open:
o[3] += o[0] == tag
if tag == "meta" and (a.get("property") or "").startswith("product:price:"):
self.meta.setdefault(a["property"], a.get("content"))
prop = a.get("itemprop")
if prop in ("price", "priceCurrency", "availability") and prop not in self.props:
self.props[prop] = a.get("content") or a.get("href") # <meta>/<link> carry the value in attributes
if tag not in ("meta", "link"):
self._open.append([tag, "prop:" + prop, [], 0])
if tag == "script" and a.get("type") == "application/ld+json":
self._open.append([tag, "ld:", [], 0])
for c in (a.get("class") or "").split():
if c in self.classes and c not in self.by_class:
self.by_class[c] = ""
self._open.append([tag, "class:" + c, [], 0])
def handle_data(self, data):
for o in self._open:
o[2].append(data)
def handle_endtag(self, tag):
for o in [o for o in self._open if o[0] == tag]:
if o[3]:
o[3] -= 1
continue
self._open.remove(o)
kind, _, name = o[1].partition(":")
text = " ".join("".join(o[2]).split())
if kind == "ld":
self.ld.append("".join(o[2]))
elif kind == "prop":
self.props[name] = self.props[name] or text
else:
self.by_class[name] = text
def stock(value):
v = str(value or "").lower().replace(" ", "")
if any(s in v for s in ("outofstock", "soldout", "discontinued")):
return False
return True if "instock" in v else None # None = the page does not say
def ld_nodes(data):
items = data if isinstance(data, list) else [data] if isinstance(data, dict) else []
for x in items:
if isinstance(x, dict):
yield x
for v in x.values():
yield from ld_nodes(v)
def from_structured(scan):
"""schema.org Offer in JSON-LD, then microdata (itemprop), then product:price meta tags."""
for blob in scan.ld:
try:
nodes = list(ld_nodes(json.loads(blob)))
except ValueError:
continue
for n in nodes:
if n.get("@type") in ("Offer", "AggregateOffer") and (n.get("price") or n.get("lowPrice")):
return {"price_text": str(n.get("price") or n.get("lowPrice")), "currency": n.get("priceCurrency"),
"in_stock": stock(n.get("availability")), "extractor": "json-ld"}
if scan.props.get("price"):
return {"price_text": scan.props["price"], "currency": scan.props.get("priceCurrency"),
"in_stock": stock(scan.props.get("availability")), "extractor": "microdata"}
if scan.meta.get("product:price:amount"):
return {"price_text": scan.meta["product:price:amount"], "currency": scan.meta.get("product:price:currency"),
"in_stock": None, "extractor": "meta"}
# Site parsers for pages without structured data: CSS class of the price and of the stock element.
SITE_PARSERS = {
"books.toscrape.com": {"price": "price_color", "stock": "availability"},
"webscraper.io": {"price": "price", "stock": None}, # product pages show no stock status
}
def extract(html, url):
site = SITE_PARSERS.get(urlparse(url).hostname.removeprefix("www."), {})
scan = PageScan([c for c in site.values() if c])
scan.feed(html)
found = from_structured(scan)
if not found and scan.by_class.get(site.get("price")):
found = {"price_text": scan.by_class[site["price"]], "currency": None, "extractor": "site:" + site["price"],
"in_stock": stock(scan.by_class.get(site["stock"])) if site.get("stock") else None}
return found
SCHEMA = {"type": "object", "additionalProperties": False,
"required": ["price_text", "list_price_text", "currency", "in_stock"],
"properties": {"price_text": {"type": ["string", "null"]}, "list_price_text": {"type": ["string", "null"]},
"currency": {"type": ["string", "null"]}, "in_stock": {"type": ["boolean", "null"]}}}
PROMPT = ("Main product on this page: price_text = the current price exactly as shown, with its currency symbol; "
"list_price_text = the crossed-out original price if one is shown, else null; currency = ISO 4217 code; "
"in_stock = true/false only if the page states it, else null. If no price is shown, price_text = null.")
def extract_with_schema(url):
"""Fallback: the API's LLM reads the page. Billed per page plus tokens. Returns (found, raw response)."""
data = scrape(url, output_formats=["markdown"], prompt=PROMPT, response_schema=SCHEMA)
sd = data.get("structured_data") or {}
return ({**sd, "extractor": "schema"} if sd.get("price_text") else None), data
# ---------- 3. Normalize ----------
class Price(NamedTuple):
amount: Decimal
currency: str | None
note: str | None = None # "from", "range" or a unit like "per lb"
SYMBOLS = {"$": "USD", "£": "GBP", "€": "EUR", "¥": "JPY", "₹": "INR"}
DOLLARS = {"USD", "CAD", "AUD", "NZD", "SGD", "HKD"}
CODES = DOLLARS | {"EUR", "GBP", "CHF", "JPY", "SEK", "NOK", "DKK", "PLN", "INR"}
NO_PRICE = re.compile(r"contact|call for|out of stock|sold out|unavailable|request a quote", re.I)
NUM = re.compile(r"\d{1,3}(?:[ \u00a0\u202f.,']\d{3})+(?:[.,]\d{1,2})?|\d+(?:[.,]\d+)?")
def to_decimal(s, decimal_sep=None):
s = re.sub(r"[ \u00a0\u202f']", "", s) # space, NBSP, narrow NBSP, Swiss apostrophe
if decimal_sep: # from the watch list: "1.299" is 1299 in de-DE but 1.299 in en-US
return Decimal(s.replace("," if decimal_sep == "." else ".", "").replace(decimal_sep, "."))
last = max(s.rfind("."), s.rfind(","))
if last != -1 and (("." in s and "," in s) or (s.count(s[last]) == 1 and len(s) - last - 1 != 3)):
return Decimal(re.sub(r"[.,]", "", s[:last]) + "." + s[last + 1:]) # last separator = decimal point
return Decimal(re.sub(r"[.,]", "", s)) # "1,299" or "1.299" guessed as thousands: pass decimal_sep
def parse_price(text, decimal_sep=None, currency=None):
"""'£51.77' -> Price(Decimal('51.77'), 'GBP'). 'Contact us', 'Out of stock' or '' -> None, never 0."""
if not text or NO_PRICE.search(text):
return None
nums = [to_decimal(m.group(), decimal_sep) for m in NUM.finditer(text)]
if not nums:
return None
code = next((c for c in sorted(CODES) if re.search(rf"\b{c}\b", text)), None)
sym = next((s for s in SYMBOLS if s in text), None)
cur = code or (currency if sym == "$" and currency in DOLLARS else SYMBOLS.get(sym)) or currency
if re.search(r"\b(from|starting at|ab)\b", text, re.I):
return Price(min(nums), cur, "from")
if len(nums) > 1 and re.search(r"\d\s*(-|–|to)\s*\D?\s*\d", text):
return Price(min(nums), cur, "range")
unit = re.search(r"(?:/|\bper\s+)\s*([a-z]{1,5})\b", text, re.I)
return Price(nums[0], cur, f"per {unit.group(1).lower()}" if unit else None)
# ---------- 4. Store ----------
DDL = """
CREATE TABLE IF NOT EXISTS observations (id INTEGER PRIMARY KEY, url TEXT, fetched_at TEXT, ok INTEGER,
error_code TEXT, raw_price_text TEXT, price TEXT, currency TEXT, list_price TEXT, in_stock INTEGER, extractor TEXT);
CREATE TABLE IF NOT EXISTS products (url TEXT PRIMARY KEY, confirmed_price TEXT, confirmed_currency TEXT,
pending_price TEXT, pending_count INTEGER DEFAULT 0, error_streak INTEGER DEFAULT 0, last_alert_at TEXT,
pending_currency TEXT);
""" # prices are TEXT, so Decimal('51.77') comes back exactly
@dataclass
class Reading:
url: str
ok: bool
error_code: str | None = None
raw_price_text: str | None = None
price: Decimal | None = None
currency: str | None = None
list_price: Decimal | None = None
in_stock: bool | None = None
extractor: str | None = None
def check(row, use_schema=False):
data = scrape(row["url"])
if not data.get("success"):
return Reading(row["url"], False, data.get("error_code") or "unknown")
found = extract(data.get("raw_content") or "", row["url"])
if not found and use_schema:
found, _ = extract_with_schema(row["url"])
r = Reading(row["url"], True, extractor=found and found["extractor"])
if found:
sep, hint = row.get("decimal_sep") or None, row.get("expected_currency") or None
p = parse_price(found["price_text"], sep, hint)
lp = parse_price(found.get("list_price_text") or "", sep, hint)
r.raw_price_text, r.in_stock, r.list_price = found["price_text"], found.get("in_stock"), lp and lp.amount
if p: # explicit currency (structured data) beats a symbol, a symbol beats the watch-list hint
r.price, r.currency = p.amount, (found.get("currency") or p.currency or "").upper() or None
return r
# ---------- 5. Diff + alert rules ----------
def should_alert(state, r, rules=RULES, now=None):
"""Pure function: (product state, new reading) -> (event, detail, new state)."""
now, s = now or datetime.now(timezone.utc), dict(state)
if not r.ok: # a failed fetch is never a price change
s["error_streak"] = (s.get("error_streak") or 0) + 1
gone = r.error_code == "host_returned_error" and s["error_streak"] >= GONE_AFTER
return ("listing_gone" if gone else "fetch_failed"), f"{r.error_code} ({s['error_streak']}x in a row)", s
s["error_streak"] = 0
if r.in_stock is False:
return "out_of_stock", "page says out of stock", s
if r.price is None: # page loaded, parser found nothing: a redesign, not a price drop
return "extractor_broken", "page loaded, no price found", s
if s.get("confirmed_price") is None:
s.update(confirmed_price=r.price, confirmed_currency=r.currency)
return "seeded", f"{r.price} {r.currency}", s
old = Decimal(s["confirmed_price"])
new_currency = r.currency != s.get("confirmed_currency") # 54.99 GBP -> 64.99 EUR is not +18%
delta = r.price - old
pct = delta / old * 100
if not new_currency and (abs(delta) < rules["min_abs"] or abs(pct) < rules["min_pct"]):
s.update(pending_price=None, pending_currency=None, pending_count=0)
return ("unchanged" if delta == 0 else "below_threshold"), f"{old} -> {r.price} ({pct:+.1f}%)", s
pending = s.get("pending_price") is not None and (Decimal(s["pending_price"]), s.get("pending_currency"))
same = pending == (r.price, r.currency) # a candidate is a price AND a currency
s.update(pending_price=r.price, pending_currency=r.currency,
pending_count=(s.get("pending_count") or 0) + 1 if same else 1)
move = (f"{s.get('confirmed_currency')} -> {r.currency} ({old} -> {r.price})" if new_currency
else f"{old} -> {r.price} {r.currency} ({pct:+.1f}%)")
detail = f"{move}, seen {s['pending_count']}/{rules['confirm_runs']} runs"
if s["pending_count"] < rules["confirm_runs"]:
return "pending", detail, s
if new_currency: # confirmed twice like a price, then fired ONCE: the new currency and price become the
# baseline, so the next run compares EUR with EUR instead of re-firing review_currency on every run
s.update(confirmed_price=r.price, confirmed_currency=r.currency,
pending_price=None, pending_currency=None, pending_count=0)
return "review_currency", detail, s
last = s.get("last_alert_at")
if last and now - datetime.fromisoformat(last) < timedelta(hours=rules["cooldown_hours"]):
return "cooldown", detail, s
s.update(confirmed_price=r.price, pending_price=None, pending_currency=None, pending_count=0,
last_alert_at=now.isoformat())
return "alert", detail, s
GROUPS = [("ALERT", {"alert"}), ("PENDING (waits for a second run)", {"pending", "cooldown"}),
("NEEDS A LOOK", {"extractor_broken", "listing_gone", "review_currency", "fetch_failed", "out_of_stock"}),
("DIGEST", {"seeded", "below_threshold", "unchanged"})]
def report(events, now):
failed = sum(e[0] in ("fetch_failed", "listing_gone") for e in events)
lines = [f"Price check {now:%Y-%m-%d %H:%M} UTC: {len(events)} URLs, {len(events) - failed} fetched OK, "
f"{failed} failed"]
for title, kinds in GROUPS:
if hits := [e for e in events if e[0] in kinds]:
lines += [f"\n{title} ({len(hits)})"] + [f" {ev:<16} {sku:<11} {d}" for ev, sku, d in hits]
return "\n".join(lines)
# ---------- 6. Run ----------
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("--urls", default="urls.csv")
ap.add_argument("--db", default="prices.db")
ap.add_argument("--schema", action="store_true", help="LLM schema fallback when no parser finds a price")
args = ap.parse_args(argv)
db = sqlite3.connect(args.db)
db.row_factory = sqlite3.Row
db.executescript(DDL)
now, events = datetime.now(timezone.utc), []
with open(args.urls, newline="") as f:
rows = list(csv.DictReader(f))
for row in rows:
r = check(row, args.schema)
db.execute("INSERT INTO observations (url, fetched_at, ok, error_code, raw_price_text, price, currency, "
"list_price, in_stock, extractor) VALUES (?,?,?,?,?,?,?,?,?,?)",
(r.url, now.isoformat(timespec="seconds"), r.ok, r.error_code, r.raw_price_text,
r.price and str(r.price), r.currency, r.list_price and str(r.list_price), r.in_stock, r.extractor))
state = db.execute("SELECT * FROM products WHERE url = ?", (r.url,)).fetchone()
event, detail, s = should_alert(dict(state) if state else {}, r, now=now)
db.execute("INSERT OR REPLACE INTO products VALUES (?,?,?,?,?,?,?,?)",
(r.url, s.get("confirmed_price") and str(s["confirmed_price"]), s.get("confirmed_currency"),
s.get("pending_price") and str(s["pending_price"]), s.get("pending_count") or 0,
s["error_streak"], s.get("last_alert_at"), s.get("pending_currency")))
db.commit()
events.append((event, row["your_sku"], detail))
print(report(events, now))
urgent = [e for e in events if e[0] in ("alert", "extractor_broken", "listing_gone", "review_currency")]
if urgent and (hook := os.environ.get("ALERT_WEBHOOK_URL")):
requests.post(hook, json={"text": report(urgent, now)}, timeout=30)
if __name__ == "__main__":
main()
