Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 15 min read

Scraper Robustness: Layout Changes, Alarms and Retries

Series: Web Scraping lecture 6/6 (advanced). For people running a scheduled scraper like the one from lecture 5 who want to know the day it breaks, not three weeks later. By the end you will detect layout changes with sc

Series: Web Scraping lecture 6/6 (advanced). For people running a scheduled scraper like the one from lecture 5 who want to know the day it breaks, not three weeks later. By the end you will detect layout changes with schema checks and zero-result alarms, handle wrong charsets, decide what to retry and what to give up on, and emit one metrics line per run.

The scraper that crashes is not the dangerous one. The dangerous one keeps running after the site redesign, reports "0 changes" every morning, and the price dashboard quietly freezes. This lecture is for whoever owns that dashboard, and it ends with a checklist for the whole series.

All runs below used an Apple Silicon Mac (M1 Pro), Python 3.9.6 standard library only, and PHP 8.5.6 (php -S 127.0.0.1:18172) serving the series' practice shop, which can switch its layout and serve broken encodings and flaky responses on purpose. Paths are shortened to ~/demo/.

The silent failure, reproduced

The practice shop has three layouts, chosen by a state file:

  • v1: <li class="product"> with <span class="price">. What our parser expects.
  • v2: a redesign. Every product is now <article class="card" data-id="..."> with <span class="amount">.
  • v1b: a small change. Only the price class was renamed to price-now.

We switched the shop to v2 and ran the unchanged lecture 5 watcher:

$ echo v2 > ~/demo/shop/state/layout
$ python3 shopwatch.py; echo "exit=$?"
2026-10-31T03:00:00Z pages=10 items=0 changes=0 secs=9.1
exit=0

Ten pages fetched, zero products, zero changes, exit status 0. Nothing is wrong as far as Python is concerned: the "next" link still existed, so pagination worked, and html.parser simply never saw an <li class="product">. cron sees success. The database keeps yesterday's prices as if nothing happened.

v1b fails loudly instead, because normalize() gets None for the price:

  File "~/demo/shopwatch/shopwatch.py", line 46, in normalize
    price = raw["price"].strip().lstrip("$").replace(",", "")
AttributeError: 'NoneType' object has no attribute 'strip'

That is the better outcome. Which leads to the most common mistake.

Common mistake: "fixing" the crash with a default

The tempting patch is one line: price = (raw["price"] or "$0.00").strip(). The traceback disappears. Here is what happened on the next run against v1b:

CHANGE SKU-0001 price 62.79 -> 0.00
CHANGE SKU-0002 price 76.09 -> 0.00
CHANGE SKU-0003 price 28.99 -> 0.00
...
2026-10-31T03:00:00Z pages=10 items=200 changes=200 secs=9.1
exit=0

200 fake price drops written into the history, exit status 0. Anyone acting on those alerts acts on garbage, and the history now needs cleaning. The fix is the opposite of a default: refuse records you cannot fully read, count them, and fail the run when the count is not zero.

Schema checks and zero-result alarms

[[fig:scr-robust-checks]]

robust.py wraps the lecture 5 watcher (it imports shopwatch.py from the same folder) with four ideas: a record check for every product, a run check for the whole run, a non-zero exit status, and one metrics line as JSON.

"""robust.py - lecture 6: the lecture 5 watcher plus checks that make failures loud.
Python 3.9+ stdlib. Needs shopwatch.py (lecture 5) in the same folder. Local practice shop only.
"""
import json, logging, os, random, re, socket, sqlite3, sys, time
import urllib.error, urllib.request
from email.utils import parsedate_to_datetime
from urllib.parse import urljoin
import shopwatch as sw

logging.Formatter.converter = time.gmtime                     # log in UTC
logging.basicConfig(format="%(asctime)sZ %(levelname)s %(message)s",
                    datefmt="%Y-%m-%dT%H:%M:%S", level=logging.INFO)
log = logging.getLogger("shopwatch")
RETRY_STATUS = {429, 500, 502, 503, 504}
rng = random.Random(42)                                        # fixed seed for the jitter

class GiveUp(Exception):
    pass

def retry_after(value):
    if not value: return None
    if value.isdigit(): return int(value)
    try: return max(0, parsedate_to_datetime(value).timestamp() - time.time())
    except (TypeError, ValueError): return None

def fetch_bytes(url, retries=3, timeout=2, metrics=None):
    for attempt in range(retries + 1):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": sw.UA})
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return r.read(), r.headers
        except urllib.error.HTTPError as e:
            metrics["http_" + str(e.code)] = metrics.get("http_" + str(e.code), 0) + 1
            if e.code not in RETRY_STATUS: raise GiveUp(f"{e.code} {url}")   # 403/404: retrying won't help
            wait = retry_after(e.headers.get("Retry-After"))
        except (urllib.error.URLError, socket.timeout) as e:
            metrics["net_errors"] = metrics.get("net_errors", 0) + 1
            wait = None
        if attempt == retries: raise GiveUp(f"gave up after {retries + 1} tries: {url}")
        wait = min(60, wait if wait is not None else 2 ** attempt + rng.uniform(0, 0.5))
        metrics["retries"] = metrics.get("retries", 0) + 1
        log.warning("retry %d for %s in %.1fs", attempt + 1, url, wait)
        time.sleep(wait)

META = re.compile(rb'<meta[^>]+charset=["\']?([A-Za-z0-9_-]+)', re.I)

def decode(body, headers, metrics):
    meta = META.search(body[:2048])
    tried = [headers.get_content_charset(),                   # 1. HTTP header (can lie)
             meta.group(1).decode() if meta else None,        # 2. <meta charset> near the top
             "utf-8"]                                         # 3. default
    for i, cs in enumerate(c for c in tried if c):
        try:
            text = body.decode(cs)
        except (UnicodeDecodeError, LookupError):
            continue
        if i:  # the first candidate failed: count it so the run report shows it
            metrics["encoding_fallback"] = metrics.get("encoding_fallback", 0) + 1
            log.warning("header charset did not fit the bytes; decoded as %s", cs)
        return text
    metrics["encoding_fallback"] = metrics.get("encoding_fallback", 0) + 1
    log.warning("no declared charset fits; decoding as cp1252")
    return body.decode("cp1252", errors="replace")

SKU = re.compile(r"^SKU-\d{4}$")
def check_item(raw):
    """Return a list of problems with one raw record (empty list = OK)."""
    p = []
    if not SKU.match(raw.get("sku") or ""): p.append("sku")
    if not (raw.get("name") or "").strip(): p.append("name")
    if not re.fullmatch(r"\$\d{1,3}(,\d{3})*\.\d{2}", (raw.get("price") or "").strip()): p.append("price")
    if (raw.get("stock") or "").strip() not in ("In stock", "Sold out"): p.append("stock")
    return p

def run(start, expected_min, max_pages=50, retries=3):
    m = {"pages": 0, "items": 0, "bad_items": 0, "errors": 0}
    t0, url, good = time.perf_counter(), start, []
    while url and m["pages"] < max_pages:
        try:
            body, headers = fetch_bytes(url, retries=retries, metrics=m)
        except GiveUp as e:                                   # without this page we have no "next" link
            log.error("%s - stopping this run", e); m["errors"] += 1
            break
        p = sw.ListParser(); p.feed(decode(body, headers, m)); m["pages"] += 1
        for raw in p.items:
            problems = check_item(raw)
            if problems:
                m["bad_items"] += 1
                if m["bad_items"] <= 3: log.error("bad record %s: %s", raw.get("sku"), ",".join(problems))
            else:
                good.append(sw.normalize(raw, url))
        m["items"] += len(p.items)
        url = urljoin(url, p.next) if p.next else None
        if url: time.sleep(0.2)                               # local demo; respect Crawl-delay for real sites
    m["secs"] = round(time.perf_counter() - t0, 2)
    alarms = []
    if m["items"] == 0: alarms.append("ZERO_ITEMS")
    elif m["items"] < expected_min: alarms.append(f"FEW_ITEMS<{expected_min}")
    if m["bad_items"]: alarms.append(f"BAD_ITEMS={m['bad_items']}")
    if m["errors"]: alarms.append(f"FETCH_ERRORS={m['errors']}")
    m["alarms"] = alarms
    print(json.dumps(m, sort_keys=True))                      # one metrics line per run
    return good, alarms

if __name__ == "__main__":
    start = sys.argv[1] if len(sys.argv) > 1 else sw.BASE + "/products?page=1"
    good, alarms = run(start, expected_min=int(sys.argv[2]) if len(sys.argv) > 2 else 150)
    if alarms:
        log.error("ALARM %s - nothing stored, yesterday's data kept", " ".join(alarms))
        sys.exit(2)                                           # cron + monitoring see a non-zero exit
    db = sqlite3.connect(os.environ.get("SHOPWATCH_DB", "shop.db"), timeout=5)
    db.executescript(sw.SCHEMA)
    log.info("stored %d items, %d changes", len(good), len(sw.store(db, good, sw.utc_now())))

(The demo waits 0.2 s between pages to keep the measurements short. Against anyone else's site, use the Crawl-delay from robots.txt or at least one second, as in lecture 5.)

The same three layouts, now through robust.py:

# v1 (normal)
{"alarms": [], "bad_items": 0, "errors": 0, "items": 200, "pages": 10, "secs": 1.98}
2026-11-14T23:31:23Z INFO stored 200 items, 0 changes
exit=0

# v2 (redesign)
{"alarms": ["ZERO_ITEMS"], "bad_items": 0, "errors": 0, "items": 0, "pages": 10, "secs": 1.94}
2026-11-14T23:31:25Z ERROR ALARM ZERO_ITEMS - nothing stored, yesterday's data kept
exit=2

# v1b (price class renamed)
2026-11-14T23:31:26Z ERROR bad record SKU-0001: price
2026-11-14T23:31:26Z ERROR bad record SKU-0002: price
2026-11-14T23:31:26Z ERROR bad record SKU-0003: price
{"alarms": ["BAD_ITEMS=200"], "bad_items": 200, "errors": 0, "items": 200, "pages": 10, "secs": 1.96}
2026-11-14T23:31:28Z ERROR ALARM BAD_ITEMS=200 - nothing stored, yesterday's data kept
exit=2

Both broken layouts are now caught, nothing wrong reaches the database, and the exit status tells cron. Is it expensive? We timed check_item() on the 200 real records, 1,000 repetitions, 5 rounds: a median of 0.99 Β΅s per record, against about 6.7 Β΅s for normalize() and roughly a second of polite waiting per page. The checks are free.

How to set expected_min: start from the item counts in your own metrics lines. We used 150 for a shop that has 200. A threshold of "less than half of yesterday" also works if you store the previous count. And keep one saved HTML page per layout as a test fixture: a unit test that runs the parser on the saved page tells you, before deploy, that your parser and the site still agree.

Encoding variants: when the header lies

The shop serves two broken pages on purpose. /enc/sjis is a Japanese page in Shift_JIS with only <meta charset="Shift_JIS">. We never sent a charset from PHP, yet the header arrived as Content-Type: text/html;charset=UTF-8: PHP's default_charset setting added it. /enc/latin1 is a Spanish page in windows-1252 whose header says utf-8. Lecture 5's fetch() trusts the header:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 60: invalid start byte
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 134: invalid continuation byte

The usual quick fix, errors="replace", turns that into silent damage:

['��ド�CοΏ½g', 'οΏ½Ϋ‰οΏ½οΏ½}οΏ½O', 'οΏ½οΏ½οΏ½οΏ½mοΏ½[οΏ½gοΏ½iοΏ½`οΏ½TοΏ½j']
['CafοΏ½ molido', 'PiοΏ½ata', 'JalapeοΏ½o en lata']

decode() above tries the header, then the <meta> charset, then UTF-8, and counts every fallback:

WARNING header charset did not fit the bytes; decoded as Shift_JIS
WARNING no declared charset fits; decoding as cp1252
/enc/sjis ['ε“δΈŠγƒ©γ‚€γƒˆ', 'δΏζΈ©γƒžγ‚°', 'ζ–ΉηœΌγƒŽγƒΌγƒˆοΌˆοΌ‘οΌ•οΌ‰'] {'encoding_fallback': 1}
/enc/latin1 ['CafΓ© molido', 'PiΓ±ata', 'JalapeΓ±o en lata'] {'encoding_fallback': 1}

A run with encoding_fallback above zero still deserves a look: the cp1252 guess is a guess. For the theory and the repair of text that is already broken, see mojibake: decode, encode and fix and measuring text encoding detection.

Retries versus giving up

[[fig:scr-robust-retry]]

The rule: retry only what time can fix, and cap it. A 429 or 503 means "not now"; honour Retry-After when it is there (seconds or an HTTP date), otherwise back off exponentially with a little random jitter so many clients do not retry in lockstep (lecture 3 measured this). A 403 or 404 will not change in two seconds, and a parse failure will not change at all. A 403 in particular can mean "we do not want this bot": the right reaction is to stop and read the terms, not to try harder.

$ python3 robust.py 'http://127.0.0.1:18172/gone/products?page=1'
2026-11-14T23:33:01Z ERROR 403 http://127.0.0.1:18172/gone/products?page=1 - stopping this run
{"alarms": ["ZERO_ITEMS", "FETCH_ERRORS=1"], "bad_items": 0, "errors": 1, "http_403": 1, "items": 0, "pages": 0, "secs": 0.01}
2026-11-14T23:33:01Z ERROR ALARM ZERO_ITEMS FETCH_ERRORS=1 - nothing stored, yesterday's data kept
$ echo $?
2

To measure the trade-off we used /flaky/products: every 3rd request gets 503 with Retry-After: 1, every 7th hangs for 3 seconds while the client timeout is 2 seconds. The request counter is reset before each run, so the failure pattern is identical every time. 10 pages, 3 runs per setting:

retries products kept run time (median) what happened
0 40 / 200 0.43 s stopped at the first 503 on page 3
1 80 / 200 5.90 s a 503 followed by a timeout used up the single retry
up to 3 200 / 200 14.34 s 7 retries for 5 Γ— 503 and 2 timeouts

[[fig:scr-robust-flaky]]

The log of the 3-retry run shows the waits: Retry-After: 1 gave 1.0 s, a timeout with no header got backoff with jitter (2.3 s on the second attempt):

WARNING retry 1 for http://127.0.0.1:18172/flaky/products?page=3 in 1.0s
WARNING retry 1 for http://127.0.0.1:18172/flaky/products?page=5 in 1.0s
WARNING retry 2 for http://127.0.0.1:18172/flaky/products?page=5 in 2.3s
...
{"alarms": [], "bad_items": 0, "errors": 0, "http_503": 5, "items": 200, "net_errors": 2, "pages": 10, "retries": 7, "secs": 14.33}

Why does a failed list page stop the whole run? Because the "next" link lives on that page. Guessing page=N+1 works on our shop, but on a real site it can walk into URLs you were never linked to. For independent URLs (detail pages from your database), count consecutive failures instead and stop after, say, three in a row: if the site is down, hammering it helps nobody.

Logging and metrics that someone will read

  • One JSON line per run with pages, items, bad items, HTTP status counts, retries, encoding fallbacks, duration and alarms. Append it to a metrics.jsonl file and you can chart "items per run" with three lines of Python, or ship it to whatever monitoring you already have.
  • UTC timestamps in logs (logging.Formatter.converter = time.gmtime plus a Z), the same clock as the data from lecture 5.
  • Exit status as the contract: 0 = stored, 2 = alarm, anything else = crash. cron can mail non-empty output; a wrapper script can turn exit 2 into a chat message. Shell script robustness, cron and logging shows the wrapper side.
  • Log the first few bad records, not all 200. Three examples are enough to see "price" is the broken field.
  • Make alarms rare and real. An alarm that fires every day gets ignored. Tune thresholds from a week of metrics before you wire them to anyone's phone.

JavaScript-rendered pages: look for the JSON first

Some pages arrive almost empty and fill themselves in the browser. The practice shop's /app is one:

/app bytes: 339 items found: 0 | root text: Loading...
/api/products: pages 10 items 20 {'sku': 'SKU-0001', 'name': 'Desk lamp 1', 'price_cents': 6279, 'in_stock': True}

urllib gets the 339-byte shell and the text "Loading...". The page's script calls /api/products?page=1. In a real browser you would find that call in the developer tools' Network tab (filter by Fetch/XHR) and read its JSON directly: structured, smaller, no HTML parsing, and price already in cents. This step was described, not run, because no browser was used here. Before you use such an endpoint, check the terms: an undocumented endpoint is not an invitation, and many sites publish an official API for exactly this data.

Headless browsers (Playwright, Selenium) can run the page's JavaScript for you. They were not installed or run here. They cost a full browser per worker, are slower by orders of magnitude, and make you look more like a heavy visitor; treat them as the last resort, not the default.

Series wrap-up: checklist and ethics recap

Before you schedule any scraper:

Question Where we covered it
Is there an official API, feed or export? Use it. lecture 1
Does robots.txt allow the path? What is the Crawl-delay? lecture 1
Do the terms allow automated access and storage? Check the site's terms and your local law. lectures 1 and 4
Does the bot identify itself with a contact URL? lecture 1
Are delays, 429 handling and retry caps in place? lectures 3 and 6
Do you store only the fields you need, and no personal data you do not need? lectures 4 and 5
Is the run idempotent, with UTC timestamps and one transaction? lecture 5
Will a layout change, a wrong charset or zero results raise an alarm? lecture 6
Does a non-zero exit reach a human? lecture 6

And what we never did in this series, on purpose: bypass CAPTCHAs, rotate IPs or proxies to dodge blocks, pretend to be a browser, or log in to someone else's site to collect data. If a site says no, the answer is no; ask for access or use the official channel.

In production: a source that times out only from the server

Our other site shows the results of Mexico's national lottery, read from three CSV files that the agency publishes. A job on shared hosting refreshes them twice a day.

What the log showed. From 14 to 23 November 2026, the job's log held 20 runs, and the Mexico step failed in every one with urllib.error.URLError: <urlopen error timed out> after the 60-second timeout. On 24 November we downloaded the same three files from an ordinary home connection: HTTP 200 in about 1.5 seconds (207,807 bytes for the main file). The source was up. It just did not answer the hosting server. We do not know why; a block on data-center addresses is a guess, not something we confirmed.

What kept it from being a silent failure. The job logs the failed step as a warning and continues with the cached data. The page prints the date of that data ("Datos actualizados 21 de noviembre de 2026") and the newest draw it knows, number 4293 of 18 November, while the agency's file already listed 4294 and 4295. A reader can see the data is old, and the page never claims a freshness it does not have. (The 21 November data came from a manual run on another machine, which is why the gap is two draws and not two weeks.)

What was missing. An alarm for staleness. The same warning appeared 20 times and nobody acted on it, because a warning that fires on every run turns into noise. The check that belongs here is the zero-result alarm from earlier in this lecture, turned into time: alert when the newest draw in the cache is older than the schedule allows. The game draws three times a week, so more than about four days without a new draw means something is wrong, whatever the per-run log says.

from datetime import date, timedelta

def stale(newest_draw: date, today: date, max_gap_days: int = 4) -> bool:
    return today - newest_draw > timedelta(days=max_gap_days)

Honest limits and version notes

  • Run on Python 3.9.6 (standard library) and PHP 8.5.6's built-in server; the layouts, encodings and failures were produced by our own practice site, not observed on a real shop. Real redesigns are often partial and gradual (A/B tests), which makes the record-level check even more important.
  • Python's shift_jis codec is stricter than Windows' cp932; a page with characters such as circled numbers may need cp932. We checked only the five names shown.
  • requests, BeautifulSoup, Scrapy and Playwright were not used. Scrapy has retry and auto-throttle middleware, and requests exposes response.apparent_encoding; described from their documentation, not run here.
  • Timings come from loopback; on a real network add latency to every retry. The jitter uses random.Random(42) so the numbers repeat.

Exercises

  1. Add a "too few compared with the last run" check: read the last line of metrics.jsonl and alarm when today's items is less than half of it.
  2. A site starts returning 403 for every page after your third run of the day. Should the scraper retry with a different User-Agent? What should it do?

Answers

  1. Before run(), read the last line: last = json.loads(open("metrics.jsonl").read().splitlines()[-1])["items"] (guard for a missing file). After the run, if m["items"] < last / 2: alarms.append("DROP_VS_LAST"), then append json.dumps(m) to the file. Keep the fixed expected_min too: if the first run after a redesign is bad, "half of yesterday" will be fine tomorrow.
  2. No. Changing the User-Agent to get around a block is evasion. Stop the run (our GiveUp already does), raise an alarm, check robots.txt and the terms, lower the frequency, and contact the site owner or use their official API.

Series navigation

Originally published at tlaboratory.net. Every output in this post was copied from a real terminal run.

πŸ“° 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.