Writing Web Scrapers With LLMs in November 2026: Check the Rules First, Show the Model Real HTML, and Fail Loudly When the Page Changes

Asking a chat model to "write a scraper for this site" usually gets you something that works once. It guesses at CSS selectors it has never seen, ignores rate limits, and returns an empty list without complaint the day the site changes its layout. You can do much better by treating the model as a fast pair programmer that needs real inputs and firm constraints. This guide walks through a practical workflow for building small, polite, maintainable scrapers with an LLM's help.

Step 1: Decide whether you should scrape at all

Before writing any code, check three things yourself. A model can't make these calls for you, and it may confidently tell you something outdated.

  • Is there an API or data export? Many sites offer a public API, an RSS feed, a sitemap, or a downloadable dataset. These are more stable than HTML and usually come with clear usage terms.
  • What do the terms of service say? Some sites forbid automated access. Read the terms for the specific site, and if the data matters to a business, ask someone qualified about the legal side.
  • What does robots.txt say? Open https://example.com/robots.txt and look for Disallow rules and any Crawl-delay that applies to your user agent. Honor them.

Also avoid collecting personal data you don't need. Scraping names, emails, or profiles creates privacy obligations that a quick script is not built to handle.

Dew drops on a spider web

Every site is its own web of rules. Check them before your crawler goes anywhere. Image: Dew on spider web by Luc Viatour, CC BY-SA 3.0, via Wikimedia Commons.

Step 2: Give the model the real HTML, not a URL

Most chat models can't reliably fetch the page you mean, and even when they can, what they see may differ from what your script sees. Save a copy of the page yourself:

curl -s -A "my-research-bot/1.0 (contact: you@example.com)" \
  https://example.com/products?page=1 -o page1.html

Then trim it. A full page can be hundreds of kilobytes of scripts and styles. Paste only the part that holds the data, such as one or two product cards and the pagination block. That keeps the prompt small and stops the model from latching onto unrelated markup.

Check one more thing: open the saved file and confirm the data is actually there. If the HTML has an empty container and the content appears only in your browser, the page renders with JavaScript. In that case, look in your browser's developer tools under the Network tab for a JSON request that carries the data. Calling that endpoint directly is often simpler than running a headless browser.

Step 3: Write a prompt with explicit constraints

Be specific about the library, the output shape, and the behaviors you require. For example:

Write a Python 3.12 scraper using requests and BeautifulSoup.
Here is a trimmed sample of the page HTML: [paste]

Extract for each product: name, price (as a string, unparsed),
and the absolute product URL.
Requirements:
- Set a descriptive User-Agent with a contact address.
- Wait at least 2 seconds between requests.
- Follow the "next page" link until there is none, max 50 pages.
- Use a timeout of 15 seconds on every request.
- Retry 429 and 5xx responses up to 3 times with backoff,
  respecting a Retry-After header if present.
- If a page yields zero products, raise an error instead of
  returning an empty list.
- Write results to products.csv.
Prefer selectors based on stable attributes (data-*, itemprop,
semantic tags) over generated class names.

That last requirement matters. Class names like css-1x9k2ab come from build tools and change whenever the site redeploys. Attributes like itemprop="price" or data-product-id tend to last longer.

Step 4: Review the selectors against your sample

Don't trust the selectors until you have run them against the HTML you saved. A quick check in a Python shell is enough:

from bs4 import BeautifulSoup
soup = BeautifulSoup(open("page1.html").read(), "html.parser")
cards = soup.select("article[data-product-id]")
print(len(cards))
print(cards[0].select_one("[itemprop=name]").get_text(strip=True))

If the count is wrong, paste the result back to the model with the snippet and ask it to explain which element each selector targets. Asking for an explanation surfaces wrong assumptions faster than asking for a fix.

Watch for these common mistakes in generated code:

  • Relative URLs left as-is. Links like /item/42 need urllib.parse.urljoin with the page URL.
  • Missing fields crash the run. select_one(...).get_text() throws when the element is absent. Decide whether a missing price should skip the row or stop the job, and make the code do that on purpose.
  • Prices parsed too early. Turning "$1,299.00" or "1.299,00 €" into a float needs locale awareness. Store the raw string first and parse in a separate, tested step.
  • No timeout. A request without a timeout can hang forever.

Step 5: Be polite by default

A scraper that hammers a small site can slow it down for real visitors. Make good behavior part of the code rather than a promise:

import time, requests

session = requests.Session()
session.headers["User-Agent"] = "my-research-bot/1.0 (contact: you@example.com)"

def fetch(url, tries=3):
    for attempt in range(tries):
        r = session.get(url, timeout=15)
        if r.status_code == 429 or r.status_code >= 500:
            wait = int(r.headers.get("Retry-After", 2 ** (attempt + 2)))
            time.sleep(wait)
            continue
        r.raise_for_status()
        time.sleep(2)
        return r.text
    raise RuntimeError(f"Gave up on {url}")

Note that Retry-After can also be an HTTP date rather than a number of seconds. Ask the model to handle both, or fall back to a fixed wait when parsing fails. Also cache pages to disk during development so you aren't re-downloading the same page every time you tweak a selector.

A combine harvester working a wheat field

Good harvesting is steady and measured, not a race to strip the field. Image: A combine harvester at work in a field of wheat by Ian Calderwood, CC BY-SA 2.0, via Wikimedia Commons.

Step 6: Fail loudly when the page changes

The worst scraper bug is a silent one. The site ships a redesign, your selectors match nothing, and your job happily writes an empty CSV every night for a month. Add checks that make breakage obvious:

  1. Zero-result guard. If a page that should have items returns none, raise an error.
  2. Field completeness. If more than a small share of rows are missing a required field, stop and report it.
  3. Volume sanity. Compare today's row count with the last run. A sudden drop to a tenth is worth an alert.
  4. Saved failing page. When a check fails, write the HTML to disk. That file is exactly what you paste to the model when you ask it to update the selectors.

Step 7: Turn your samples into tests

The HTML snapshots you saved are free test fixtures. Ask the model to write a small pytest file that loads each snapshot and asserts the parsed output, like the number of items and the first item's name. When the site changes, save a new snapshot, update the parser, and add the new fixture while keeping the old one if both layouts might still appear. Keep parsing in pure functions that take HTML and return data, separate from the code that fetches pages, so these tests run offline in milliseconds.

Step 8: Know when to reach for a browser

If the data really only exists after JavaScript runs and there is no usable JSON endpoint, a headless browser such as Playwright is the next step. It is slower and heavier, so use it only for the pages that need it. The same rules apply: wait for a specific element rather than sleeping for a fixed time, keep the request rate low, and keep the guards from Step 6. If a site puts up a login wall or a challenge page, treat that as the site telling you no rather than a puzzle to defeat.

A quick checklist

  • Checked for an API, read the terms, and honored robots.txt.
  • Gave the model trimmed, real HTML and explicit requirements.
  • Verified every selector against saved snapshots.
  • Set a contact User-Agent, timeouts, delays, and retry limits.
  • Added zero-result and completeness checks that fail loudly.
  • Wrote offline tests from saved pages.

Used this way, an LLM saves you the tedious parts of scraping, like boilerplate, retry logic, and selector drafts, while you keep control of the parts that need judgment: whether to scrape, how hard to hit a site, and how to notice when things break.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)

Tencent Hy4 Preview: Open 770B MoE Built for Real Work