Sub topic 7
Respecting robots.txt
This chapter assumes you have read the chapters on fetching pages and on the URL frontier. You should be comfortable with HTTP status codes and with reading short Python programs.
What robots.txt is
robots.txt is a plain text file served at the root of a site, for example https://example.com/robots.txt. Site owners use it to tell crawlers which paths they may fetch. The format is standardized as the Robots Exclusion Protocol (RFC 9309).
The file is a request, not access control. Nothing stops a crawler from ignoring it. A well-behaved crawler follows it anyway, because ignoring it gets your crawler blocked and can cause legal and reputational trouble.
Three scoping rules matter for design:
- A robots.txt file applies to one origin: the combination of scheme, host, and port.
http://example.com,https://example.com, andhttps://blog.example.comeach have their own file. - It controls crawling (fetching). It does not control indexing. The
X-Robots-Tagheader and<meta name="robots">tags cover indexing and are a separate topic. - It covers paths on that origin only. A path that is allowed for one agent may be disallowed for another.
The file format
A file is a list of groups. Each group starts with one or more User-agent lines, followed by Allow and Disallow rules.
User-agent: *
Disallow: /private/
Crawl-delay: 5
User-agent: MyCrawler
Allow: /search/help
Disallow: /search
Sitemap: https://example.com/sitemap.xmlThe rules for reading it are:
- Pick the one group whose
User-agentbest matches your product token (for exampleMyCrawler). If none matches, use the*group. If there is no*group, everything is allowed. - Groups are not merged across different agents. In the file above,
MyCrawlerobeys only its own group. The/private/rule from*does not apply to it. - Within the group, the most specific rule wins. RFC 9309 defines this as the longest matching path, and
Allowwins a tie. - Rules are path prefixes.
Disallow: /searchblocks/search,/search?q=x, and/searching. An emptyDisallow:blocks nothing. - An empty or missing rule set means everything is allowed.
Major crawlers also support two wildcards in paths. * matches any run of characters, and $ anchors the end of the URL. For example, Disallow: /*.pdf$ blocks URLs that end in .pdf.
Sitemap: lines are independent of groups and point to sitemap files. Crawl-delay is not part of the RFC. Some crawlers honor it and Google ignores it, so treat it as a hint you may adopt.
Checking rules with the standard library
RobotFileParser.parse() accepts lines of text, so you can test rules without a network:
from urllib.robotparser import RobotFileParser
ROBOTS = """\
User-agent: *
Disallow: /private/
Crawl-delay: 5
User-agent: MyCrawler
Disallow: /search
"""
rp = RobotFileParser()
rp.parse(ROBOTS.splitlines())
print(rp.can_fetch('MyCrawler', 'https://example.com/search?q=x')) # False
print(rp.can_fetch('MyCrawler', 'https://example.com/private/a')) # True
print(rp.can_fetch('OtherBot', 'https://example.com/private/a')) # False
print(rp.crawl_delay('MyCrawler')) # None
print(rp.crawl_delay('OtherBot')) # 5The second line shows the no-merge rule at work. MyCrawler has its own group, so the /private/ rule is not applied to it.
Gotchas in the standard parser
The standard parser is good for learning and for simple crawlers, but it differs from RFC 9309 in ways that matter:
- First match wins. It uses the first rule in file order that matches, not the longest. If
Disallow: /searchappears beforeAllow: /search/help, the help page is reported as blocked. - No wildcards. It does not understand
*or$inside paths. It treats them as literal characters, soDisallow: /*.pdf$blocks nothing. - Status handling.
read()treats 401 and 403 as "disallow everything" and other 4xx as "allow everything". The RFC treats all 4xx responses as "file unavailable, crawling allowed". - No timeout.
read()has no timeout argument, so a slow server can stall your crawler.
For a serious crawler, fetch the file yourself with your own timeout and size limit, then pass the text to parse(). If you need exact RFC matching, use a library that implements it or write the longest-match logic yourself.
What to do when the fetch fails
The status code you get for /robots.txt determines what you may do next.
| Response | Meaning | Action |
|---|---|---|
| 2xx | File exists | Parse it and obey it |
| 3xx | Redirect | Follow up to about five hops, then treat as unavailable |
| 4xx | No file for you | Treat as no rules; crawl freely |
| 5xx or network error | Server problem | Assume everything is disallowed, retry later |
| Too large | File over 500 KiB | Parse only the first 500 KiB |
Treating a 5xx as "disallow all" is the cautious choice. A site that is failing may have simply lost its configuration, and you do not want to crawl private paths because of a temporary error.
A caching layer for the crawler
Fetching robots.txt before every page would double your traffic. Cache one parsed result per origin. Cache successful results for up to 24 hours, which is what the RFC suggests. Cache failures for a shorter time so the crawler retries soon.
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit
from urllib.robotparser import RobotFileParser
AGENT = 'MyCrawler'
TTL = 24 * 3600
RETRY_AFTER_ERROR = 15 * 60
MAX_ROBOTS_BYTES = 500 * 1024
class RobotsCache:
def __init__(self, agent=AGENT):
self.agent = agent
self.entries = {} # origin -> (expires_at, parser)
def _load(self, origin):
req = urllib.request.Request(
origin + '/robots.txt', headers={'User-Agent': self.agent}
)
rp = RobotFileParser()
try:
with urllib.request.urlopen(req, timeout=10) as resp:
text = resp.read(MAX_ROBOTS_BYTES).decode('utf-8', errors='replace')
rp.parse(text.splitlines())
return time.monotonic() + TTL, rp
except urllib.error.HTTPError as err:
if 400 <= err.code < 500:
rp.allow_all = True
return time.monotonic() + TTL, rp
rp.disallow_all = True
except OSError:
rp.disallow_all = True
return time.monotonic() + RETRY_AFTER_ERROR, rp
def _get(self, url):
parts = urlsplit(url)
origin = f'{parts.scheme}://{parts.netloc}'
cached = self.entries.get(origin)
if cached is None or cached[0] <= time.monotonic():
cached = self._load(origin)
self.entries[origin] = cached
return cached[1]
def allowed(self, url):
return self._get(url).can_fetch(self.agent, url)
def crawl_delay(self, url):
return self._get(url).crawl_delay(self.agent)HTTPError is a subclass of OSError, so its except clause must come first. Redirects are followed by urlopen automatically.
Wiring it into the crawl loop
The crawl loop from the earlier chapter checks robots.txt after taking a URL from the frontier. That has a cost: the frontier has already spent that host's politeness slot on a URL you then skip. Two refinements help:
- Check
allowed()when you enqueue a link as well as when you dequeue it. Blocked links then never occupy frontier space. Re-check at dequeue time, because a cached file may have expired and changed. - Feed
crawl_delay()into the frontier. Usemax(default_delay, declared_delay)for that host, so a site that asks for 5 seconds gets 5 seconds.
The robots.txt fetch is itself a request to the host. It should go through the same per-host delay logic as any other fetch, or your first contact with a host will ignore politeness.
Common errors
- Using one cache entry for a whole domain. Scheme, host, and port each produce a separate origin.
- Matching on your full user-agent string. Match on the product token only, such as
MyCrawler, notMyCrawler/1.2 (+https://example.com/bot). - Treating a 5xx as "no file". This crawls blocked paths during outages.
- Never refreshing the cache. A long-running crawl must re-fetch after the TTL.
- Assuming
Disallowhides content. The URL may still appear in links elsewhere. If you must keep content out of results, that is an indexing concern.
Exercise
A site's robots.txt returns a 503 response when your crawler requests it. A teammate proposes treating this the same as a 404, so the crawler can proceed. Explain why this is risky, and describe what the crawler should do instead.
Show answer
A 404 means the site has no robots.txt, so all paths are allowed. A 503 means the server is failing, and the real file may exist and contain Disallow rules. Treating it as a 404 could fetch paths the owner has blocked. The crawler should treat the origin as fully disallowed for now, cache that result for a short time (minutes, not a day), and retry the robots.txt fetch later. When it gets a 2xx or 4xx response, it applies the normal rules.