How to check robots.txt in Python before you fetch a page

Checked on 2026-11-24.

Python's standard library answers the question in a few lines: urllib.robotparser reads a site's robots.txt, and can_fetch() says whether a crawler may fetch an address. Since Python 3.13.14, 3.14.5 and 3.15.0 it matches rules the way RFC 9309 specifies; older versions apply them in file order and do not treat * as a wildcard. What it leaves to you is fetching the file well.

1. urllib.robotparser

From the module's documentation:

Python
import urllib.robotparser

rules = urllib.robotparser.RobotFileParser()
rules.set_url("https://docs.apify.com/robots.txt")
rules.read()

print(rules.can_fetch("ExampleBot", "https://docs.apify.com/academy"))   # True or False
print(rules.crawl_delay("ExampleBot"))   # None when no Crawl-delay applies to it
print(rules.site_maps())                 # None when the file names no sitemap

can_fetch(useragent, url) returns True if the user agent "is allowed to fetch the url according to the rules contained in the parsed robots.txt file". crawl_delay(), request_rate() and site_maps() return the file's Crawl-delay, Request-rate and Sitemap values, or None, and mtime() the time the file was fetched. Pass the short name robots.txt groups address, such as ExampleBot, not your whole User-Agent header; the module cuts ExampleBot/1.0 at the slash and ignores case.

What RFC 9309 says, and which Pythons follow it

The Robots Exclusion Protocol was published as a Standards Track RFC in September 2022: RFC 9309. Its main rules:

  • The file is /robots.txt at the top of the host, UTF-8 and text/plain.
  • A crawler finds its group by its product token, case-insensitively. Groups for the same token are combined, and when none matches, the * group applies.
  • Of the allow and disallow rules that match, "the most specific match found MUST be used", meaning the longest one; when an allow and a disallow rule are equivalent, the allow rule should win. * stands for any characters and $ for the end of the address. /robots.txt itself is always allowed.
  • A 4xx answer means the file is "unavailable", and the crawler "MAY access any resources on the server". A 5xx answer or a network error means it is unreachable, and the crawler "MUST assume complete disallow".
  • Crawlers should follow at least five redirects and should not use a cached copy for more than 24 hours. Any limit they set on how much of the file they parse must be at least 500 kibibytes.

Python's module followed older, unofficial rules until 2026. The changelogs say which releases have the new ones:

Change3.133.143.15
Longest match, * and $, combined groups (gh-138907)3.13.143.14.53.15.0
An unreachable robots.txt means disallow all (gh-79638)3.13.153.14.73.15.0

On an older Python, such as 3.12, the first matching rule in the file decides, and a * inside a path is compared as a literal character, so a rule such as Disallow: /*.pdf$ does not stop PDF files. sys.version_info tells you which you have. If you cannot upgrade, use Protego, below.

2. Fetch the file yourself

read() is the weak part. In the module's source, it calls urllib.request.urlopen() without a timeout of its own and under urllib's default user agent, Python-urllib/ and the version. A 401 or 403 answer makes every address disallowed, a choice the source explains as "most likely this applies to the entire site", while the RFC counts both among the 4xx answers after which a crawler may access anything. A network error is raised to you as an exception. So fetch the file with your own client and hand the lines to parse():

Python
# pip install requests
import urllib.robotparser
from urllib.parse import urlsplit

import requests

AGENT = "ExampleBot"   # your crawler's product token: the name robots.txt groups address
HEADERS = {"User-Agent": f"Mozilla/5.0 (compatible; {AGENT}/1.0; +https://www.example.com/bot.html)"}
DISALLOW_ALL = ["User-agent: *", "Disallow: /"]


def robots_rules(page_url):
    """A parser for the site of page_url, with RFC 9309's rules for each kind of answer."""
    parts = urlsplit(page_url)
    robots_url = f"{parts.scheme}://{parts.netloc}/robots.txt"
    rules = urllib.robotparser.RobotFileParser(robots_url)
    try:
        res = requests.get(robots_url, headers=HEADERS, timeout=15)   # redirects are followed
    except requests.exceptions.RequestException:
        rules.parse(DISALLOW_ALL)   # unreachable: assume complete disallow
        return rules
    if res.status_code >= 500:
        rules.parse(DISALLOW_ALL)   # unreachable: assume complete disallow
    elif res.status_code in (401, 403):
        rules.parse(DISALLOW_ALL)   # refused: what read() does as well
    elif res.status_code >= 400:
        rules.parse([])             # unavailable, such as 404: no rules apply
    else:
        text = res.content[: 500 * 1024].decode("utf-8", "replace")   # RFC 9309: at least 500 KiB
        rules.parse(text.splitlines())
    return rules


page = "https://docs.apify.com/academy"
rules = robots_rules(page)
print(rules.can_fetch(AGENT, page))
print(rules.can_fetch("GPTBot", page))   # the same page, for another crawler's group
print(rules.crawl_delay(AGENT), rules.site_maps())

Requests follows redirects by default, and the sample cuts the file at 500 KiB, the smallest limit the RFC allows. It treats 401 and 403 the way read() does; under the RFC you may treat them as "unavailable" instead, so choose on purpose. For a long crawl, keep one parser per host and fetch the file again when mtime() is more than a day old.

The GPTBot line asks the same file about another crawler. OpenAI's crawler documentation says "Disallowing GPTBot indicates a site's content should not be used in training generative AI foundation models".

3. Protego, for older Pythons and Scrapy

Protego (0.7.0, September 21, 2026) is a pure-Python parser that "implements the parsing and URL matching rules of RFC 9309" and also reads Crawl-delay, Request-rate, Visit-time and Host. Its README is plain about the rest: "Fetching robots.txt is up to you", status codes, redirects, caching and the parsing limit included.

Python
# pip install protego requests
import requests
from protego import Protego

res = requests.get("https://docs.apify.com/robots.txt", timeout=15)
rules = Protego.parse(res.text)
print(rules.can_fetch("https://docs.apify.com/academy", "ExampleBot"))   # address first, then agent
print(rules.crawl_delay("ExampleBot"), list(rules.sitemaps))

Note the order: Protego's can_fetch() takes the address first and the agent second, the opposite of the standard library's. Scrapy uses it by default (ROBOTSTXT_PARSER is scrapy.robotstxt.ProtegoRobotParser). Scrapy's settings documentation also notes that ROBOTSTXT_OBEY defaults to False "for historical reasons" but is switched on in the settings.py that scrapy startproject generates.

Crawl-delay and other lines outside the standard

RFC 9309 says crawlers "MAY interpret" records it does not define, naming Sitemaps as the example, and crawlers differ: Google's robots.txt documentation says "other fields such as crawl-delay aren't supported". For a small crawler, honoring a delay a site asks for is still the polite choice.

4. An API that obeys robots.txt for you

The Pipefetch page content endpoint fetches one page and returns its content as Markdown. robots.txt is respected: a page the site's robots.txt closes to crawlers is not read, and the request answers 404 not_allowed at no cost.

Python
import os
import requests

res = requests.get(
    "https://pipefetch.com/v1/web/content",
    params={"url": "https://docs.apify.com/academy"},
    headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
    timeout=90,
)
if res.status_code == 404:
    code = res.json()["error"]["code"]   # never charged
    if code == "not_allowed":
        print("robots.txt closes this page to crawlers, so it was not read")
    else:
        print(code)   # page_not_found, needs_javascript, no_content, website_blocked, website_unreachable
else:
    res.raise_for_status()
    page = res.json()["data"]
    print(page["title"], page["wordCount"])

The tech stack endpoint reports on the file itself, among the rest of a site's stack: whether it has one, its address, the sitemaps the site lists, and whether it blocks AI crawlers and which.

Python
import os
import requests

res = requests.get(
    "https://pipefetch.com/v1/web/tech",
    params={"url": "stripe.com"},
    headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
    timeout=90,
)
if res.status_code == 404:
    print(res.json()["error"]["code"])   # website_unreachable or website_blocked: not charged
else:
    res.raise_for_status()
    pages = res.json()["data"]["pages"] or {}
    print(pages.get("hasRobotsTxt"), pages.get("robotsTxtUrl"), pages.get("sitemapUrls"))
    print(pages.get("blocksAiCrawlers"), pages.get("blockedAiAgents"))

For stripe.com, our saved answer of November 19, 2026 holds hasRobotsTxt true, robotsTxtUrl https://stripe.com/robots.txt, one sitemap and blocksAiCrawlers false.

Where it stops: the content endpoint takes no user agent, so it cannot answer for your own crawler's group, and not_allowed does not say which rule matched; the tech endpoint returns the facts above, not the rules. Each request costs 1 credit, only when it returns data, and most take 2 to 9 seconds. A new account has 100 free credits and needs no card. Pipefetch is not affiliated with the websites it reads.

Which one should you use?

SituationUse
Your own crawler, on Python 3.13.14, 3.14.5, 3.15 or laterurllib.robotparser, with the file fetched as in the second sample
An older Python, or a crawler built on ScrapyProtego
You want page content and would rather not fetch or check anything yourselfThe page content endpoint, which skips closed pages for free
An overview of many sites: robots.txt, sitemaps, AI-crawler blocksThe tech stack endpoint

What robots.txt is and is not

The RFC is direct about it: "These rules are not a form of access authorization." The file is a request from the site's owner, and listing a path there makes it public rather than hiding it. A page robots.txt allows can still be covered by the site's terms, and a page it disallows is a clear statement of what the owner wants. This is not legal advice. To turn the pages you may fetch into text, the web page to Markdown guide picks up where this one ends.

Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.

Free tools for this

Every source

YouTube

Instagram

TikTok

Facebook

Google

Threads

LinkedIn

App stores

Steam

X

Pinterest

Airbnb

Real estate

Keywords

Job boards

Eventbrite

Shopify stores

Public tenders

All guides