Skip to content

Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.

fix(robots): don't patch robotparser on Python 3.14+ (#2278)

Nasrin6218bb815c52
diff --git a/crawl4ai/utils.py b/crawl4ai/utils.py
index f4cb7a62..d6f9118c 100644
--- a/crawl4ai/utils.py
+++ b/crawl4ai/utils.py
@@ -50,27 +50,34 @@ from urllib.parse import (
import inspect
-# Monkey patch to fix wildcard handling in urllib.robotparser
-from urllib.robotparser import RuleLine
-import re
-
-original_applies_to = RuleLine.applies_to
-
-def patched_applies_to(self, filename):
- # Handle wildcards in paths
- if '*' in self.path or '%2A' in self.path or self.path in ("*", "%2A"):
- pattern = self.path.replace('%2A', '*')
- pattern = re.escape(pattern).replace('\\*', '.*')
- pattern = '^' + pattern
- if pattern.endswith('\\$'):
- pattern = pattern[:-2] + '$'
- try:
- return bool(re.match(pattern, filename))
- except re.error:
- return original_applies_to(self, filename)
- return original_applies_to(self, filename)
-
-RuleLine.applies_to = patched_applies_to
+# Monkey patch to fix wildcard handling in urllib.robotparser.
+# Python 3.14 rewrote robotparser with native wildcard, '$' and RFC 9309
+# longest-match support, and its applies_to returns a match *length* used to
+# rank rules. Patching it there returns a bool, which collapses every wildcard
+# rule to the lowest priority and breaks Allow: overrides -- so only patch the
+# older implementation, which has no wildcard support at all.
+import sys
+
+if sys.version_info < (3, 14):
+ from urllib.robotparser import RuleLine
+
+ original_applies_to = RuleLine.applies_to
+
+ def patched_applies_to(self, filename):
+ # Handle wildcards in paths
+ if '*' in self.path or '%2A' in self.path or self.path in ("*", "%2A"):
+ pattern = self.path.replace('%2A', '*')
+ pattern = re.escape(pattern).replace('\\*', '.*')
+ pattern = '^' + pattern
+ if pattern.endswith('\\$'):
+ pattern = pattern[:-2] + '$'
+ try:
+ return bool(re.match(pattern, filename))
+ except re.error:
+ return original_applies_to(self, filename)
+ return original_applies_to(self, filename)
+
+ RuleLine.applies_to = patched_applies_to
# Monkey patch ends
def chunk_documents(
@@ -252,8 +259,14 @@ class VersionManager:
def _preserve_bare_query(rules_text: str) -> str:
"""Append '*' to Allow/Disallow values ending in a bare '?' (e.g. '/*?').
- '/*?' and '/*?*' allow/deny exactly the same URLs; the rewrite only
- survives parsers that would otherwise drop the trailing '?'.
+ Only correct below Python 3.14, and only called there. Those parsers drop a
+ trailing '?' when normalizing the rule path, collapsing '/*?' to '/*' and
+ blocking the whole site; they also take the first matching rule, so making a
+ rule longer cannot change which one wins.
+
+ From 3.14 the stdlib keeps the '?' and ranks rules by match length, and the
+ rewrite becomes actively wrong: '/*?*' matches to end of string, so it
+ outranks a competing 'Allow: /*?q=' that the raw '/*?' would have lost to.
"""
fixed = []
for raw_line in rules_text.splitlines():
@@ -372,9 +385,12 @@ class RobotsParser:
# Create parser for this check
parser = RobotFileParser()
- # Old Pythons drop a trailing '?' from rules, so '/*?' becomes
- # '/*' and blocks the whole site. '/*?*' matches the same URLs.
- parser.parse(_preserve_bare_query(rules).splitlines())
+ # Below 3.14, rewrite rules ending in a bare '?' so they survive path
+ # normalization. From 3.14 the stdlib handles them, and the rewrite
+ # would skew its longest-match ranking -- see _preserve_bare_query.
+ if sys.version_info < (3, 14):
+ rules = _preserve_bare_query(rules)
+ parser.parse(rules.splitlines())
# If parser can't read rules, allow access
if not parser.mtime():
diff --git a/tests/unit/test_robots_query_rules.py b/tests/unit/test_robots_query_rules.py
index e88e57bb..67ce1bc4 100644
--- a/tests/unit/test_robots_query_rules.py
+++ b/tests/unit/test_robots_query_rules.py
@@ -6,6 +6,7 @@ the rule to the equivalent '/*?*', which survives the round trip.
"""
import asyncio
+import sys
import pytest
@@ -86,3 +87,77 @@ def test_ordinary_rules_still_apply(tmp_path):
rules = "User-agent: *\nDisallow: /private/\nAllow: /public/\n"
assert _can_fetch(rules, "/public/page", tmp_path) is True
assert _can_fetch(rules, "/private/secret", tmp_path) is False
+
+
+def test_wildcard_patch_is_scoped_to_old_pythons():
+ """The patch must be installed exactly where it is needed, and nowhere else.
+
+ Python 3.14 supports wildcards natively and ranks rules by match length; the
+ patch returns a bool, which would flatten that ranking (see crawl4ai.utils).
+ """
+ from urllib.robotparser import RuleLine
+
+ is_patched = RuleLine.applies_to.__name__ == "patched_applies_to"
+ assert is_patched == (sys.version_info < (3, 14))
+
+
+ "path, expected",
+ [("/a.php", False), ("/deep/a.php", False), ("/a.html", True)],
+)
+def test_wildcard_rules_work_on_every_python(path, expected, tmp_path):
+ """Wildcard support is the whole point of the patch - it must survive the gate."""
+ rules = "User-agent: *\nDisallow: /*.php\n"
+ assert _can_fetch(rules, path, tmp_path) is expected
+
+
+ sys.version_info < (3, 14),
+ reason="longest-match Allow precedence only exists in the 3.14+ stdlib parser",
+)
+ "path, expected",
+ [("/public/a.html", True), ("/private/a.html", False), ("/public/a.txt", False)],
+)
+def test_allow_overrides_broad_disallow(path, expected, tmp_path):
+ """Regression: the old unconditional patch denied /public/a.html on 3.14."""
+ rules = "User-agent: *\nDisallow: /\nAllow: /public/*.html\n"
+ assert _can_fetch(rules, path, tmp_path) is expected
+
+
+# A narrower Allow: competing with the bare-'?' Disallow:. On 3.14 the stdlib
+# ranks rules by match length, and rewriting '/*?' to '/*?*' makes the Disallow
+# match to end of string -- so the rewrite would beat the Allow: and deny a URL
+# robots.txt permits. Below 3.14 the first matching rule wins regardless of
+# length, so the rewrite is safe there and the Allow: still loses to nothing.
+COMPETING_RULES = "User-agent: *\nAllow: /*?q=\nDisallow: /*?\n"
+
+
+ sys.version_info < (3, 14),
+ reason="longest-match Allow precedence only exists in the 3.14+ stdlib parser",
+)
+ "path, expected",
+ [("/search?q=1", True), ("/search?x=1", False), ("/search", True)],
+)
+def test_query_allow_outranks_bare_query_disallow(path, expected, tmp_path):
+ """Regression: _preserve_bare_query must not run on 3.14.
+
+ '/*?*' matches longer than '/*?q=', so the rewrite would flip /search?q=1
+ from allowed to denied.
+ """
+ assert _can_fetch(COMPETING_RULES, path, tmp_path) is expected
+
+
+ sys.version_info >= (3, 14),
+ reason="pre-3.14 parsers take the first matching rule, not the longest",
+)
+ "path, expected",
+ [("/search?q=1", True), ("/search?x=1", False), ("/search", True)],
+)
+def test_query_allow_still_wins_below_py314(path, expected, tmp_path):
+ """The same rules must give the same answers below 3.14, via the rewrite."""
+ assert _can_fetch(COMPETING_RULES, path, tmp_path) is expected