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:
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 sitemapcan_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.txtat the top of the host, UTF-8 andtext/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
allowanddisallowrules 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.txtitself 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:
| Change | 3.13 | 3.14 | 3.15 |
|---|---|---|---|
Longest match, * and $, combined groups (gh-138907) | 3.13.14 | 3.14.5 | 3.15.0 |
| An unreachable robots.txt means disallow all (gh-79638) | 3.13.15 | 3.14.7 | 3.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():
# 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.
# 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.
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.
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?
| Situation | Use |
|---|---|
| Your own crawler, on Python 3.13.14, 3.14.5, 3.15 or later | urllib.robotparser, with the file fetched as in the second sample |
| An older Python, or a crawler built on Scrapy | Protego |
| You want page content and would rather not fetch or check anything yourself | The page content endpoint, which skips closed pages for free |
| An overview of many sites: robots.txt, sitemaps, AI-crawler blocks | The 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
APIs used in this guide
-
1 credit
Website Tech Stack API
The technologies a website runs on, by category, with its hosting, DNS, email setup, tracking ids and security headers.
GET /v1/web/tech -
1 credit
Web Page to Markdown API
The content of one web page as Markdown or text, without its menus, with title, headings and word and token counts.
GET /v1/web/content
More Websites guides
- Clearbit Logo API alternatives: get a company logo from its domain
- How to extract email addresses from a website in Python
- How to turn a web page into Markdown in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to build a LangChain tool that reads web pages and searches Google
- How to turn a web page into Markdown in JavaScript for RAG
- How to extract social media links from a website in Python
- How to get a website's favicon in Python
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
- How to give an LLM live Google results with tool calling
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python