Skip to main content

Recheck the rules each run: read robots.txt before every crawl

Have the scheduled crawl fetch robots.txt first, save it as that day's file, and skip the crawl with exit 4 when the rules block the start page.

From our run on
  1. rules: 404, 5 lines saved to runs/robots-2026-11-21.txt, start page allowed (no rules)
  2. log: 2026-11-21T05:19:25Z  https://quotes.toscrape.com/  rules=allowed  pages=20  ok
Lesson 15 of 20 12 min read

To keep a scheduled crawl inside a site's current rules, have the script fetch robots.txt at the start of every run, save it as runs/robots-YYYY-MM-DD.txt, and crawl only when those rules allow the start page. When the rules block it, or the file cannot be read, the run sends no crawl request, logs a skipped line and exits 4.

At the end of this lesson you have recheck_rules.py, a copy of the site's robots.txt in runs/ for each day the job ran, a rules= field in every log line, and a run you made stand aside on purpose.

Rules last read in lesson 3

After lesson 14, the job takes a lock, crawls up to 20 pages, replaces runs/latest.csv only when the run looks whole, as in lesson 12, and writes one log line. Lesson 13 handed it to cron. Nothing has read the site's robots.txt since lesson 3, by hand. A site can rewrite that file any morning, and an unwatched job will go on crawling a path it has since closed.

Why once per run

RFC 9309 limits how long a crawler may rely on a copy it read earlier: "Crawlers SHOULD NOT use the cached version for more than 24 hours, unless the robots.txt file is unreachable." Python's documentation for RobotFileParser expects the same habit, describing its mtime() method as "useful for long-running web spiders that need to check for new … files periodically." This script has no use for mtime(). Each run is a fresh process that starts with no copy, so it asks every time and judges by whatever answer comes back.

That answer is only as fresh as the request allows. The API's cache option defaults to true, with a two-day window, and the recorded script leaves it on, so its runs cannot show how old their copy was. Your copy turns it off.

What the script does with the answer follows the status, as lesson 3's script did. A 4xx means no rules apply. Any status that is neither 200 nor 4xx means the rules could not be read, and the RFC says that for a server error "the crawler MUST assume complete disallow."

What recheck_rules.py adds

Compared with lesson 14's script, these lines are new or changed:

  • Imports for urljoin and RobotFileParser, and an AGENT constant set to *.
  • API is now the bare host, and one call() helper sends both the /scrape request for the rules and the /crawl request.
  • A log() helper, because the run can now end in two places that each write a line.
  • Before the crawl, a /scrape call for /robots.txt with return_format set to raw. Whatever comes back is written to runs/robots-YYYY-MM-DD.txt, under a first line that records the status.
  • A verdict: allowed or blocked from can_fetch on a 200, allowed (no rules) on a 4xx, unreachable on anything else. A run that is not allowed logs pages=0 skipped and returns 4 before the crawl request is built.
  • The log line gains rules=, and the refusal from lesson 14 no longer prints its second line.

The robots file name carries the date and no time, so a second run on the same day writes over that day's copy. One file per day is what the comparison further down works from.

It takes the key from SPIDER_API_KEY, the same variable every lesson uses. The recorded version below sends no user_agent and no delay, and it stops with a traceback if the robots request itself fails, so read it here and make the edits in the next section before you run or schedule your copy. This is the script exactly as it ran on 2026-11-20 and 2026-11-21, under Python 3.14.7:

"""The course job: read the site's robots.txt, then crawl at most 20 pages if the rules allow
it, save the run, and replace runs/latest.csv only when the run looks whole.
Only one copy runs at a time.

    python3 recheck_rules.py URL

Each run saves the robots.txt it read as runs/robots-YYYY-MM-DD.txt and prints one verdict
line, so a change in the rules shows up the day it happens. A 4xx answer means no rules
and every path is allowed (RFC 9309 2.3.1.3). Any other answer that is not 200 means the
rules are unreachable, and the job crawls nothing (RFC 9309 2.3.1.4).
Exit 0: the run replaced latest.csv.
Exit 1: the key is missing or nothing came back.
Exit 2: the run was held, as in lesson 12.
Exit 3: another run is still going, as in lesson 14.
Exit 4: the rules block the start page or could not be read, so nothing was crawled.
"""
import csv
import fcntl
import json
import os
import shutil
import sys
import urllib.request
from datetime import datetime, timezone
from urllib.parse import urljoin
from urllib.robotparser import RobotFileParser

API = "https://api.spider.cloud"
AGENT = "*"
LATEST = os.path.join("runs", "latest.csv")
LOG = os.path.join("runs", "log.txt")
LOCK = os.path.join("runs", "job.lock")


def call(path, params, key):
    req = urllib.request.Request(API + path, data=json.dumps(params).encode(), headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=300) as resp:
        got = json.load(resp)
    return got if isinstance(got, list) else [got]


def count_rows(path):
    if not os.path.exists(path):
        return 0
    with open(path, newline="", encoding="utf-8") as f:
        return max(sum(1 for _ in csv.reader(f)) - 1, 0)


def log(line):
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(line + "\n")
    print(f"log: {line}")


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: python3 recheck_rules.py URL")
        return 1
    url = sys.argv[1]
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    os.makedirs("runs", exist_ok=True)
    lock = open(LOCK, "a+", encoding="utf-8")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        lock.seek(0)
        print(f"another run is still going: {lock.read().strip()}")
        return 3
    started = datetime.now(timezone.utc)
    lock.truncate(0)
    lock.write(f"started {started:%Y-%m-%dT%H:%M:%SZ}, pid {os.getpid()}\n")
    lock.flush()
    stamp = f"{started:%Y-%m-%dT%H:%M:%SZ}"

    robots = call("/scrape", {"url": urljoin(url, "/robots.txt"), "request": "http",
                              "return_format": "raw"}, key)[0]
    status, text = robots.get("status"), robots.get("content") or ""
    saved = os.path.join("runs", started.strftime("robots-%Y-%m-%d.txt"))
    with open(saved, "w", encoding="utf-8") as f:
        f.write(f"# status {status}\n{text}")
    rules = RobotFileParser()
    if status == 200:
        rules.parse(text.splitlines())
        verdict = "allowed" if rules.can_fetch(AGENT, url) else "blocked"
    elif status and 400 <= status < 500:
        rules.parse([])
        verdict = "allowed (no rules)"
    else:
        verdict = "unreachable"
    print(f"rules: {status}, {len(text.splitlines())} lines saved to {saved}, start page {verdict}")
    if not verdict.startswith("allowed"):
        log(f"{stamp}  {url}  rules={verdict}  pages=0  skipped")
        return 4

    pages = call("/crawl", {"url": url, "limit": 20, "request": "http",
                            "return_format": "markdown"}, key)
    if not pages:
        print("nothing came back")
        return 1
    rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
                   for p in pages))
    out = os.path.join("runs", started.strftime("quotes-%Y-%m-%dT%H%M%SZ.csv"))
    with open(out, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["url", "status", "bytes"])
        writer.writerows(rows)

    before = count_rows(LATEST)
    whole = all(s == 200 for _, s, _ in rows) and len(rows) >= 0.8 * before
    if whole:
        shutil.copyfile(out, LATEST)
    log(f"{stamp}  {url}  rules={verdict.split()[0]}  pages={len(rows)}  {'ok' if whole else 'held'}")
    return 0 if whole else 2


if __name__ == "__main__":
    sys.exit(main())

Make your copy before you run it

Copy the script to recheck_rules.py and change four places. First, name your bot, so can_fetch reads the group a site writes for you and not only the * group:

AGENT = "examplebot"

Second, replace the robots request and the file write under it. Your bot's name goes on the request, and "cache": False asks for the file as the site serves it now. Any failure of the request leaves status empty: an HTTP error from the API, a timeout, a cut-off response, a body that is not JSON, an empty list, or a 200 that came back with no content at all. An empty status falls through to unreachable, so the run still saves the day's file with the reason in it, logs a skipped line and returns 4:

    saved = os.path.join("runs", started.strftime("robots-%Y-%m-%d.txt"))
    try:
        robots = call("/scrape", {"url": urljoin(url, "/robots.txt"), "request": "http", "return_format": "raw",
                                  "cache": False,
                                  "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)"}, key)[0]
        status, body = robots.get("status"), robots.get("content")
        if status == 200 and body is None:
            raise ValueError("status 200 with no content")
        text = body or ""
    except Exception as err:
        status, text = None, f"# not read: {err!r}\n"
    with open(saved, "w", encoding="utf-8") as f:
        f.write(f"# status {status}\n{text}")

The except is wide on purpose. A cut-off response raises http.client.IncompleteRead, which is neither an OSError nor a ValueError. For this one request, any error means the same thing: the rules were not read, so nothing gets crawled.

Third, add a branch for 429 above the 4xx branch. The recorded script counts a 429 as one more 4xx and crawls. A 429 is the site asking you to slow down, so your copy skips the crawl and leaves the next try to tomorrow's scheduled run:

    elif status == 429:
        verdict = "rate-limited"
    elif status and 400 <= status < 500:

Fourth, name your bot on the crawl too and space its requests a second apart:

    pages = call("/crawl", {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
                            "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}, key)

Now run your copy once by hand against the practice quotes site:

python3 recheck_rules.py https://quotes.toscrape.com/
echo $?

You should see a rules: line and a log: line in the same shape as the two below, and echo $? should print 0. When it does, open your crontab with crontab -e and change the script name in lesson 13's line to recheck_rules.py. Any unattended web scraping job needs this step, because the rules you read on the first day are only the rules of that day.

Two days of verdicts

Both recorded runs used the saved version above, without your four edits. They were started by hand, not by cron, with the same command against the same site.

The first run, on 2026-11-20 at 22:37 UTC, printed these two lines and exited 0:

rules: 404, 5 lines saved to runs/robots-2026-11-20.txt, start page allowed (no rules)
log: 2026-11-20T22:37:04Z  https://quotes.toscrape.com/  rules=allowed  pages=20  ok

The second, on 2026-11-21 at 05:19 UTC, printed the same verdict and also exited 0:

rules: 404, 5 lines saved to runs/robots-2026-11-21.txt, start page allowed (no rules)
log: 2026-11-21T05:19:25Z  https://quotes.toscrape.com/  rules=allowed  pages=20  ok

Read the verdict lines

On both days the site answered 404 for /robots.txt. The script reads any 4xx as no rules, so the crawl went ahead. The 5 lines are the body of the 404 page, not rules, and the run records kept only what the script printed, so this page cannot show them. Had the answer been 429, the recorded script would have crawled anyway. Your copy exits 4.

The log line keeps the first word of the verdict, rules=allowed. The rest is lesson 12's format, where ok means every page answered 200 and latest.csv was replaced.

Neither day reached exit 4. On a day the rules block the start page or cannot be read, the first line ends in start page blocked or start page unreachable, the log line ends pages=0 skipped, no crawl request goes out, and lesson 13's cron output shows exit=4.

The verdict covers the start page only. The script does not test each page the crawl reaches against the rules. Lesson 3's read_robots.py gives you a verdict for any path you hand it.

Compare one day with the last

The script judges each day on its own and never opens yesterday's file. A change that still allows the start page, such as a new Disallow line for /tag/, leaves rules=allowed exactly as it read the day before. Catching that change is your check, not the script's. When you read the log, compare the two newest robots files in runs/:

ls runs/robots-*.txt | tail -n 2
diff $(ls runs/robots-*.txt | tail -n 2)

The names start with the date, so ls sorts them oldest first and tail picks the last two days the job ran. diff prints nothing when the files match and the differing lines when they do not. You need two days of files before it has anything to compare. The two recorded runs did not keep their robots files, so there is no diff of theirs to print here.

When the lines differ, read the new ones against the paths you crawl, and look at the site's terms again while you are there. A script could flag the difference, but whether a new line touches your job is something you decide by reading it.

Try it yourself

Make the script stand aside on purpose, without depending on any real site's rules. The test below swaps call() for a stand-in that answers the robots request with a file that disallows everything, and stops with a message if a crawl request is ever built. No request leaves your machine, so your key is never sent, though SPIDER_API_KEY still has to be set, as in lesson 1, because the script checks for it first. Work in a new folder, because the daily file name carries no host and would write over today's quotes copy:

mkdir try-blocked && cp recheck_rules.py try-blocked/ && cd try-blocked
python3 - <<'EOF'
import sys
import recheck_rules as job

def stand_in(path, params, key):
    if path == "/crawl":
        sys.exit("a crawl request was built")
    return [{"status": 200, "content": "User-agent: *\nDisallow: /\n"}]

job.call = stand_in
sys.argv = ["recheck_rules.py", "https://quotes.toscrape.com/"]
sys.exit(job.main())
EOF
echo $?

You are done when the first line reports status 200 and ends in start page blocked, echo $? prints 4, and runs/log.txt in that folder holds one line ending in pages=0 skipped. If you see a crawl request was built, the check after the verdict is missing from your copy. Change the stand-in's answer to {"status": 503, "content": ""} and run it again: the line should end in start page unreachable and the exit should still be 4.

Do this, avoid this

Do this

  • Fetch robots.txt at the top of every run, before the crawl request is built.
  • Save each day's file with its status line, whatever the status was.
  • Exit 4 with a skipped log line when the start page is blocked, the site answers 429, or the rules cannot be read.
  • Diff the two newest robots files when you read the log, and reread the site's terms when they differ.

Avoid this

  • Crawling on yesterday's verdict when today's robots fetch failed.
  • Counting the lines of a 404 body as rules.
  • Running two sites from one runs folder, since the daily file name has no host in it.
  • Skipping the diff because the verdict still says allowed.

Next

The two quotes runs left two dated robots files, two log lines with rules=allowed and two exits of 0. Lesson 16 asks what a full week of those files and lines tells you when you read them side by side.

Sources

  1. RFC 9309, Robots Exclusion Protocol, IETF, September 2022 Read
  2. Python documentation, urllib.robotparser, Parser for robots.txt Read

Run this on a page you care about

The playground sends the request this page describes and shows you the response. Keyless runs work without an account and are rate limited.