Loading WURK...
RomanMotion
RomanMotion
Product ad & launch videos · 3D product visuals · app & AI builder. Concept to final cut in days. Open for projects.

Scrape a website politely with your coding agent: robots.txt, delays and caching

Give your coding agent a scraper that checks site rules, slows down, saves pages locally, and stops when a site says wait.

Published on November 11, 20267 min read

You asked your coding agent to collect information from a website, and it produced a scraper that works. Then the requests pile up, the site starts returning errors, and you’re left wondering whether the data is complete. A few rules in your brief can make the scraper easier on the site and easier for you to check.

Start by looking for an official API, RSS feed, or export. If scraping is appropriate, read the site’s terms and robots.txt, identify your scraper, space out requests, and save downloaded HTML locally. Keep fetching separate from parsing, and stop when the site asks you to wait.

Check the site before writing code

A website may already offer the information you need in a downloadable file, feed, or documented API. Those options can save you from maintaining a parser when the page layout changes.

If you still need to scrape, read the site’s terms and its robots.txt file. You’ll usually find the latter at the site’s root, such as https://example.com/robots.txt. It contains instructions for automated crawlers, including rules for particular user agents and paths.

RFC 9309 describes the Robots Exclusion Protocol and makes an important distinction: robots rules are not access authorization. A path that appears allowed in robots.txt is not, by itself, permission to ignore the site’s terms. When in doubt, ask the site owner.

Python’s urllib.robotparser can check whether a user agent may fetch a URL according to a parsed robots file. Check the rules by eye too, particularly if they use wildcards or overlapping paths: the module is older than the RFC, and an issue on Python's tracker covers bringing it in line with RFC 9309.

For a first run, choose one public page you’re allowed to access. Don’t point an untested script at the whole site.

This research step is work an agent can do for you before it writes a line of code, as long as you tell it to stop and report what it found. If you want an agent setup to try it with, you can try the zcode agent harness free.

Give your agent a polite-scraping brief

Replace the bracketed parts and paste this into your coding agent:

I want to collect [specific data] from [site].

First, check whether the site provides an official API, RSS
feed, or export. Read its terms and robots.txt. Summarize what
you found and stop if access is unclear.

If scraping is appropriate, write a Python script that:
- Uses a User-Agent identifying my project and contact.
- Checks robots.txt for that same user agent before fetching.
- Requests only the URLs I approve, with a delay between requests.
- Stops on network errors, redirects, or unsuccessful responses.
- Stops on 429 or 503 and reports any Retry-After header.
- Saves permitted raw HTML to a local cache for later runs.
- Does not re-download a cached page on an ordinary rerun.
- Keeps fetching separate from parsing and parsed output.
- Does not access private pages or bypass restrictions.

Show me the code and how to run it. Test with local fixtures
or a site I control, and report what you actually tested.

The delay needs to fit the site. A value that seems slow on your laptop is not a universal permission slip. Follow any published limits and choose a more conservative pace when you’re unsure.

Also decide how fresh the data needs to be. A cache is useful precisely because it avoids another download, but yesterday’s saved page may not reflect today’s content.

A small fetcher with a local cache

This example fetches one approved public URL. It checks robots.txt on each run, waits before fetching the page, and saves the response body in raw_html/. An ordinary rerun reuses the saved page.

Install the dependency:

python3 -m pip install requests

Save the script as fetch.py. Change the bot name and contact to your own details before using it.

import hashlib
import sys
import time
from pathlib import Path
from urllib.parse import urlsplit
from urllib.robotparser import RobotFileParser

import requests

BOT = "MyResearchBot"
CONTACT = "[email protected]"  # Replace with a real contact.
WAIT_SECONDS = 2  # Example only; follow the site's limits.

if CONTACT == "[email protected]":
    sys.exit("Set CONTACT to your real contact details.")
if len(sys.argv) != 2:
    sys.exit("Usage: python3 fetch.py <url>")

url = sys.argv[1]
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or not parts.netloc:
    sys.exit("Provide a full HTTP or HTTPS URL.")
if parts.username or parts.password:
    sys.exit("Do not put credentials in the URL.")

headers = {"User-Agent": f"{BOT} ({CONTACT})"}
robots_url = f"{parts.scheme}://{parts.netloc}/robots.txt"


def get_or_stop(address):
    try:
        response = requests.get(
            address, headers=headers, timeout=20,
            allow_redirects=False,
        )
    except requests.RequestException as error:
        sys.exit(f"Request failed: {error}")

    if response.status_code != 200:
        wait = response.headers.get("Retry-After", "not provided")
        sys.exit(
            f"Stopped: HTTP {response.status_code}; "
            f"Retry-After: {wait}"
        )
    return response


robots = get_or_stop(robots_url)
parser = RobotFileParser()
parser.parse(robots.content.decode("utf-8-sig").splitlines())

if not parser.can_fetch(BOT, url):
    sys.exit("Stopped: robots.txt disallows this URL.")

name = hashlib.sha256(url.encode("utf-8")).hexdigest() + ".html"
path = Path("raw_html") / name

if path.exists():
    print(f"Using cached page: {path}")
else:
    crawl_delay = parser.crawl_delay(BOT) or 0
    rate = parser.request_rate(BOT)
    rate_delay = rate.seconds / rate.requests if rate else 0
    time.sleep(max(WAIT_SECONDS, crawl_delay, rate_delay))

    page = get_or_stop(url)
    if "no-store" in page.headers.get("Cache-Control", "").lower():
        sys.exit("Stopped: the response says not to store it.")

    path.parent.mkdir(exist_ok=True)
    path.write_bytes(page.content)
    print(f"Saved page: {path}")

Run it with the permitted page URL in place of the example:

python3 fetch.py "https://example.com/some-public-page"

I tested it against a small local site with a robots.txt that blocks one folder: the first run waited, then saved the page; the second run used the cache without a request; the blocked URL and a missing page both stopped with exit code 1 and a reason.

The delay shown is an example, not a recommended rate for every site. This script also stops on redirects or an unavailable robots.txt; it doesn’t treat either as permission to continue. The Requests documentation explains timeouts, headers, and redirect handling.

The script is deliberately small: it doesn’t coordinate separate runs or multiple computers. Don’t launch copies in parallel or repeatedly restart it to get around the delay. Test it against local fixtures or a site you control before using it elsewhere.

Stop, wait, and parse separately

A 429 response means the site is asking you to slow down; a 503 can mean the service is unavailable. Either may include Retry-After. As MDN explains, that value can be a number of seconds or an HTTP date.

The example prints the header and exits. It does not retry automatically or remember a waiting period across restarts. If you see Retry-After, wait as instructed before trying again. If it’s absent, stop and investigate rather than repeatedly rerunning the script.

The fetcher saves the HTML response body without parsing it. Ask your agent to build a separate parser that reads files from raw_html/ and writes its results to a different folder. If you fix a selector or change an output column, you can rerun the parser against the saved page without contacting the site. It also means your agent can iterate on the parser as many times as it needs without touching the network; if those sessions add up, this link gets you 10% off GLM coding plans.

Review a saved page alongside the parsed output. A missing field might mean the layout changed, the page needs client-side rendering, or the parser is looking in the wrong place. Keep the raw files only as permitted by the site’s terms, and avoid caching private or sensitive content.

Checklist before the first run

  • I checked for an API, RSS feed, or export
  • I read the terms and checked robots.txt
  • The User-Agent identifies my project and has a real contact
  • The script requests only approved URLs
  • The delay follows the site’s published limits
  • Errors, redirects, and unavailable robots rules stop the run
  • A 429, 503, or Retry-After won’t trigger a tight retry loop
  • Raw HTML and parsed results are stored separately
  • I tested with a local fixture or a site I control
  • I know when the cache needs refreshing

More notes from building with coding agents are on our blog.

If this saved you an afternoon, a small tip on this post helps keep these guides coming.

Conversation

Join the conversation

Share your thoughts with the author and other readers.

Comments0

Checking your account…

Latest comments

0
No comments yet. Be the first to share your thoughts.