Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Keep a weekly screenshot archive of competitor pricing pages and get told when they change

Competitors change their pricing pages quietly: a plan gets renamed, a price moves by five dollars, a feature leaves the cheaper tier. You notice months later, when nobody remembers what the page said. A weekly screensho

Competitors change their pricing pages quietly: a plan gets renamed, a price moves by five dollars, a feature leaves the cheaper tier. You notice months later, when nobody remembers what the page said. A weekly screenshot archive gives you a dated record, and a script that compares each week with the last tells you which pages to look at. The hard part is not taking the screenshots; it is not crying wolf every week. Public pages only.

Why this is harder than it looks

Two screenshots of the same pricing page a week apart almost never match pixel for pixel, even when nothing that matters changed:

  • Rotating content. Promo banners, testimonial carousels, logo strips and countdown timers change on every visit.
  • Dates. "Prices updated 9 November" changes on its own.
  • Height shifts. One extra line in a banner pushes everything below it down, and a naive diff reports the whole page as changed.
  • Viewport and format. A 1366-pixel capture cannot be compared with a 1920 one, and JPEG compression makes slightly different pixels each time. Fix the device and use PNG.
  • The change you care about is tiny. In my test, changing one plan price from $29 to $35 changed 379 pixels: 0.04% of a full-page screenshot. A rotating banner and a date line on the same page changed 4,796 pixels, more than ten times as many. No percentage threshold separates those two. Perceptual hashes do not help either; they are designed to ignore small changes, and a new price is a small change.

So the work is mostly in removing noise before the diff, not in the diff itself.

The method

  1. Fix the capture. Same device, PNG, same settings every week.
  2. Hide what rotates. Banners, carousels, chat widgets and date lines are hidden by CSS selector before capture.
  3. Clip to what matters. For a pricing page, capture only the pricing table element.
  4. Archive by date and URL, one folder per week, so any two weeks can be compared later.
  5. Diff with a tolerance, then count. Ignore small per-pixel differences (anti-aliasing), count the pixels that still differ, and flag a page above an absolute count, not a percentage.
  6. Save a picture of the change, with changed pixels painted red, so a person can judge it in seconds.

Configure the capture

Website Screenshot API renders each URL in headless Chromium, stores the image in the run's key-value store, and returns a record with screenshotUrl, width, height and format. The inputs that matter here:

  • device: laptop (1366x768) by default. Never change it once chosen.
  • format: png.
  • hideCookieBanners: on by default; hides 60+ common consent pop-ups with CSS, clicking nothing.
  • hideSelectors: elements to hide. They get display: none, so the layout closes up around them the same way every week.
  • clipSelector: capture one element, such as #pricing, instead of the page.
  • fullPage, autoScroll, unstickFixed: on by default, so full-page captures load lazy images and show sticky headers once. They are skipped when you clip.

hideSelectors and clipSelector apply to every URL in a run, and each competitor marks up its pricing table differently, so save one task per site in the Apify Console. For a pricing page (placeholder domain):

{
    "urls": ["https://competitor-a.example/pricing"],
    "device": "laptop",
    "format": "png",
    "hideCookieBanners": true,
    "hideSelectors": [".promo-banner", ".testimonial-carousel", ".last-updated", "#intercom-container"],
    "clipSelector": "#pricing"
}

Find selectors with your browser's Inspect tool, and prefer stable IDs over generated class names such as .css-1x9f2k, which change with every deploy. For home pages, use a separate task without clipSelector and with a longer hideSelectors list.

Schedule each task weekly in the Console, or call it from cron and save the dataset:

curl -X POST "https://api.apify.com/v2/acts/josh99smith~website-screenshot-api/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" -d @competitor-a.json -o results.json

Compare with last week

The script reads results.json, downloads each screenshot into archive/<date>/, finds the most recent earlier copy of the same URL, and compares them. It needs Python 3.8+ and Pillow (pip install pillow).

import datetime
import json
import re
import sys
import urllib.request
from pathlib import Path

from PIL import Image, ImageChops

PIXEL_TOLERANCE = 40  # grey levels (0-255); smaller differences are anti-aliasing noise
ALERT_PIXELS = 150  # flag a page when more pixels than this changed; a new price is a few hundred

results, archive = sys.argv[1], Path(sys.argv[2])
today = sys.argv[3] if len(sys.argv) > 3 else datetime.date.today().isoformat()
(archive / today).mkdir(parents=True, exist_ok=True)


def slug(url):
    return re.sub(r"[^a-z0-9]+", "-", url.lower().split("://", 1)[-1]).strip("-")[:80]


def previous(name):
    older = sorted(d for d in archive.iterdir() if d.is_dir() and d.name < today and (d / name).exists())
    return older[-1] / name if older else None


def compare(old_path, new_path, diff_path):
    old = Image.open(old_path).convert("L")
    new = Image.open(new_path).convert("L")
    if old.width != new.width:
        return None, f"width {old.width} -> {new.width}, not comparable (check the device preset)"
    h = min(old.height, new.height)
    delta = ImageChops.difference(old.crop((0, 0, old.width, h)), new.crop((0, 0, new.width, h)))
    mask = delta.point(lambda v: 255 if v > PIXEL_TOLERANCE else 0)
    changed = mask.histogram()[255] + abs(old.height - new.height) * old.width
    box = mask.getbbox()
    note = f"changed area x {box[0]}-{box[2]}, y {box[1]}-{box[3]}" if box else "no pixel changes"
    if old.height != new.height:
        note += f"; height {old.height} -> {new.height}"
    if box:  # fade this week's image and paint the changed pixels red
        faded = Image.blend(new.convert("RGB"), Image.new("RGB", new.size, "white"), 0.6)
        faded.paste((255, 0, 0), (0, 0, new.width, new.height), mask.crop((0, 0, new.width, new.height)))
        faded.save(diff_path)
    return changed, note


alerts = []
for rec in json.load(open(results, encoding="utf-8")):
    if not rec.get("success"):
        print(f"FAILED   {rec['url']}: {rec.get('errorType')} {rec.get('error', '')[:80]}")
        continue
    name = slug(rec["url"]) + "." + ("jpg" if rec["format"] == "jpeg" else "png")
    new_path = archive / today / name
    urllib.request.urlretrieve(rec["screenshotUrl"], new_path)
    old_path = previous(name)
    if old_path is None:
        print(f"BASELINE {rec['url']} ({rec['width']}x{rec['height']})")
        continue
    changed, note = compare(old_path, new_path, new_path.with_suffix(".diff.png"))
    flagged = changed is None or changed > ALERT_PIXELS
    if flagged:
        alerts.append(rec["url"])
    print(f"{'CHANGED ' if flagged else 'same    '} {rec['url']} vs {old_path.parent.name}: "
          f"{'n/a' if changed is None else changed} px; {note}")

print(f"\n{len(alerts)} page(s) with more than {ALERT_PIXELS} changed pixels:", ", ".join(alerts) or "none")

Run python weekly_diff.py results.json archive each week. Files are keyed by the input url, not by screenshotKey, because the key includes the URL's position in the input list and only the host name.

What it looked like in a test

I tested the chain on a locally served mock pricing page: sticky header, promo banner, a "prices checked" date, three plan cards and a testimonial carousel. Week 2 changed only the banner, date and carousel. Week 3 changed them again and raised the Pro plan from $29 to $35.

  • Plain full page: week 2 reported 4,796 changed pixels and week 3 reported 5,021. Both flagged, and the real change was buried in the noise.
  • With hideSelectors: week 2 reported 0 pixels, week 3 reported 379 in a box around the Pro price.
  • With clipSelector: "#pricing": the same, 0 and 379, on an image a third of the size.

The .diff.png painted the Pro price red and nothing else.

How to read the output

  • BASELINE is the first week for a URL.
  • CHANGED lines give the pixel count and bounding box. Open the .diff.png; if the red is a price, plan name or feature row, open both screenshots side by side.
  • A height change usually means a row was added or removed. Everything below it counts as changed, so read the box, not the count.
  • Width not comparable means the device setting changed. Re-baseline.
  • FAILED with Element not found for clipSelector is news in itself: the page was redesigned. Find the new selector and re-baseline.

If one page keeps flagging for the same harmless element, add that element to hideSelectors rather than raising ALERT_PIXELS.

Cost and limits

The Actor charges $0.005 per screenshot (PDFs are off unless enabled). Five competitors with a pricing page and a home page each is 10 screenshots a week: 10 x $0.005 = $0.05. A year of weekly runs is 520 screenshots, $2.60. Pages that fail to load and missing clip targets are free failure records, and each run stops at the maximum cost you set.

Limits to plan around:

  • Download every week. Images live in the run's key-value store, which Apify deletes after your plan's data retention period. The script copies them into your archive.
  • Public pages only. The Actor does not log in or get past bot protection; such pages come back as blocked.
  • One browser's view. Prices that vary by country or A/B test show whatever the run got. If that matters, use a fixed proxy country (proxy traffic is billed separately).
  • Very tall pages can be truncated by Chromium, another reason to clip.

Keep the archive for internal reference, and respect the sites' terms and copyright.

If this saves you time, a review on the Store page helps other people find it, and a star on GitHub helps too.

Disclosure: I built this Actor. Source: github.com/josh99smith/website-screenshot-api.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.