Skip to main content

Read robots.txt: work out which paths a crawler may fetch

Fetch a site's robots.txt, decide by hand which of five paths your crawler may request, then check your verdicts against Python's own parser.

From our run on
  1. url: https://www.rfc-editor.org/robots.txt
  2. status: 200
  3. lines: 5
  4. allowed: /rfc/rfc9309.html
  5. blocked: /rfc/authors/
Lesson 3 of 20 9 min read

To read robots.txt, find the group of rules whose User-agent line names your crawler, or the * group when no group names it, and check each path you want against that group's Disallow and Allow lines. Of the rules that match the start of the path, the longest one decides. A path that no rule matches is allowed, and so is every path when no group applies to you at all.

By the end of this lesson you have read_robots.py, a script that fetches a site's robots.txt, prints every line of it, and says allowed or blocked for each path you hand it. You also have something the script cannot give you: five verdicts you reached by hand before you ran it, so you know why each answer came out the way it did.

The rules you need for the hand check

A handful of sentences from RFC 9309 cover the hand check. The robots.txt page covers the rest of the format.

Finding your group comes first. The RFC says "Crawlers MUST use case-insensitive matching to find the group that matches the product token", and the product token is the short name of your crawler. It adds that the token "SHOULD be a substring in the User-Agent header", so the name you check with is the name your requests carry. This lesson uses examplebot.

Matching a path comes second. In the RFC's words, "The matching MUST start with the first octet of the path." A rule is a prefix, so Disallow: /rfc/authors/ covers /rfc/authors/ and everything under it, and says nothing about /rfc/rfc9309.html. When more than one rule matches, "The most specific match found MUST be used." Most specific means longest: the RFC counts the octets in each matching rule, and the rule with the most wins. So with Disallow: /docs/ and Allow: /docs/public/, the path /docs/public/a.html is allowed, because the Allow rule is longer. If an Allow and a Disallow rule are the same length, the RFC recommends following the Allow. When no rule matches, the RFC is just as direct: "If no match is found amongst the rules in a group for a matching user-agent or there are no rules in the group, the URI is allowed."

Two more cases sit before the matching. If no group names your crawler and the file has no * group either, no rules apply to you and every path is allowed. If two groups name the same crawler, the RFC has you combine their rules into one group before you match.

A Sitemap line is not a rule. Skip it when you check by hand.

These sentences are enough for the two files in this lesson, which use plain prefixes and one group. Other files can use * inside a path to match any run of characters and $ to mark the end of a path. Read section 2.2 of the RFC, or the robots.txt page, before you check another site's file by hand.

What the script adds

Lesson 2 ended with check_page.py, which fetched one page, checked its status and looked for one word. This script keeps the same skeleton: the key check, the urllib.request call to the API, and main() returning the exit code. The changes are in what it fetches and what it does with the answer.

The arguments are now a site, an agent name and one or more paths. The request asks for {site}/robots.txt with return_format set to raw, so the file comes back as the plain text the site wrote. The word check is gone. In its place are a branch for each kind of status, a loop that prints the file line by line, and the standard library's RobotFileParser, which Python's documentation says "answers questions about whether or not a particular user agent can fetch a URL on the website that published the" file. Its can_fetch method, per the same page, "Returns True if the useragent is allowed to fetch the url according to the rules contained in the parsed robots.txt file."

The script reads your API key from the SPIDER_API_KEY environment variable, as lessons 1 and 2 did. Save it as read_robots.py. Both runs below came from this version, unchanged, so you can repeat them and compare line for line.

"""Fetch a site's robots.txt through the Spider API and say which paths a crawler may fetch.

    python3 read_robots.py SITE AGENT PATH [PATH ...]

Exit 0: the rules were read, or the site has no file, and every path was checked.
Exit 1: the key is missing, or the file is unreachable, so nothing may be fetched.
"""
import json
import os
import sys
import urllib.request
from urllib.robotparser import RobotFileParser

API = "https://api.spider.cloud/scrape"


def main() -> int:
    if len(sys.argv) < 4:
        print("usage: python3 read_robots.py SITE AGENT PATH [PATH ...]")
        return 1
    site, agent, paths = sys.argv[1].rstrip("/"), sys.argv[2], sys.argv[3:]
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    body = json.dumps({"url": f"{site}/robots.txt", "request": "http", "return_format": "raw"}).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=60) as resp:
        page = json.load(resp)
    if isinstance(page, list):
        page = page[0]

    status = page.get("status") or 0
    print(f"url: {page.get('url')}")
    print(f"status: {status}")
    if 400 <= status < 500:
        # RFC 9309 2.3.1.3: an unavailable file means no rules, so every path may be fetched.
        print("no rules: every path is allowed")
        lines = []
    elif status != 200:
        # RFC 9309 2.3.1.4: an unreachable file means the whole site is off limits for now.
        print("rules unreachable: every path is blocked, try again later")
        return 1
    else:
        lines = (page.get("content") or "").splitlines()
    print(f"lines: {len(lines)}")
    for line in lines:
        print(f"  | {line}")
    rules = RobotFileParser()
    rules.parse(lines)
    for path in paths:
        verdict = "allowed" if rules.can_fetch(agent, f"{site}{path}") else "blocked"
        print(f"{verdict}: {path}")
    return 0


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

Paths go in without the site in front, because the script joins the two itself.

Run one: a file with rules

The first site is the one that publishes the RFC. Before you run anything, write these five paths down and leave a space beside each for your verdict. Both runs below were made on 2026-11-20 with Python 3.14.7, and each one exited 0.

python3 read_robots.py https://www.rfc-editor.org examplebot /rfc/rfc9309.html /rfc/authors/ /rfc/rerendered/rfc9110.html /rfc/v3test/ /info/rfc9309

Cover the bottom of the output and read only the file it printed, the five lines that start with a bar.

url: https://www.rfc-editor.org/robots.txt
status: 200
lines: 5
  | User-agent: *
  | Disallow: /rfc/authors/
  | Disallow: /rfc/rerendered/
  | Disallow: /rfc/v3test/
  | Sitemap: https://www.rfc-editor.org/sitemap.xml
allowed: /rfc/rfc9309.html
blocked: /rfc/authors/
blocked: /rfc/rerendered/rfc9110.html
blocked: /rfc/v3test/
allowed: /info/rfc9309

Work it through. No group names examplebot, so the * group is yours. It holds three Disallow lines and no Allow lines.

  • /rfc/rfc9309.html starts with /rfc/, but none of the three rules is a prefix of it. Allowed.
  • /rfc/authors/ is exactly the first rule. Blocked.
  • /rfc/rerendered/rfc9110.html starts with /rfc/rerendered/. Blocked, even though the rule does not name that file.
  • /rfc/v3test/ is exactly the third rule. Blocked.
  • /info/rfc9309 matches nothing. Allowed.

Now uncover the last five lines. Two allowed and three blocked, the same as your list. If one of yours differs, find the rule line you used and check it against the prefix sentence above.

Run two: a site with no file

The second site is a quotes site built for scraping practice. The paths are its front page, a listing page, a tag, an author and the login form.

python3 read_robots.py https://quotes.toscrape.com examplebot / /page/2/ /tag/love/ /author/Albert-Einstein/ /login
url: https://quotes.toscrape.com/robots.txt
status: 404
no rules: every path is allowed
lines: 0
allowed: /
allowed: /page/2/
allowed: /tag/love/
allowed: /author/Albert-Einstein/
allowed: /login

There was no file to read, so the hand check is one step. RFC 9309 section 2.3.1.3 treats a status in the 400 range as unavailable, and says that then "the crawler MAY access any resources on the server". All five paths are allowed, and the parser, given zero lines, agrees.

That verdict covers robots.txt only. A missing file says nothing about the site's terms of use, and it does not mean any rate of requests is welcome. Lesson 4 deals with the rate.

The case neither run shows

The script has a third branch. Any status that is neither 200 nor in the 400 range prints a line saying every path is blocked and returns 1. For a 5xx, that is what section 2.3.1.4 asks: when the file is unreachable through server errors, "the crawler MUST assume complete disallow." The RFC treats redirects and other answers separately. Blocking on those too is this script's own choice, the safe one while you are learning. Neither site above answered that way, so there is no output to show here. If you see exit 1 after a status: line, fetch nothing from that site and try the file again later.

Send the name you check with

The script as printed, the one that made both runs above, sends no user_agent. That keeps it the same as the start of lesson 2, so your output can match the dated runs. Once you have matched them, change the body so the request carries the name you pass as AGENT. Then the group you checked is the group the site sees. This version was not used for the runs above, and for these two files it gives the same verdicts, because neither file names any crawler:

    body = json.dumps({
        "url": f"{site}/robots.txt",
        "request": "http",
        "return_format": "raw",
        "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)",
    }).encode()

Put your own crawler's name where examplebot is, the same name you pass as AGENT. Identify your crawler explains what belongs in that string. The same check is the first thing to do on any new host in a web scraping job.

Try it yourself

Pick a documentation site you use, open its /robots.txt in a browser, and choose five paths on it: at least one you expect to be blocked and one you expect to be allowed. Write your five verdicts on paper, with the rule line that decided each, before you run read_robots.py with your site, your crawler's name and those paths. You are done when the script's five allowed: and blocked: lines match what you wrote, or when you can point to the rule that explains each one that does not.

Look at the status: line first. The script reads every status in the 400 range as "no rules", and that includes 429. A 429 does not mean the file is missing. It means the site wants you to slow down. If you see it, stop, send nothing more to that site, and wait as the Retry-After page explains before you ask for the file again.

Do this, avoid this

Do this

  • Write a verdict and the deciding rule line for every path before you run the parser.
  • Pass the same name as AGENT that your User-Agent header carries.
  • Look at the url line on a 404 to confirm the script asked for the right site.
  • Read the site's terms of use as well when its robots.txt is missing.

Avoid this

  • Fetching any path on a site whose robots.txt came back with a 5xx.
  • Reading a 429 on robots.txt as a missing file. It means wait.
  • Passing full addresses as paths, since the script adds the site in front.
  • Counting a Sitemap line as a rule when you check by hand.
  • Checking paths against one group while your requests send a different name.

Next: how fast

The script now knows which paths it may ask for on rfc-editor.org and on the practice site. Lesson 4 asks the question that comes before fetching all five of them: how long should the script wait between two requests to the same host?

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.