Scrapy, a fast high-level web crawling & scraping framework for Python.
Keep robots.txt rules of HTTP and HTTPS URLs apart (#8435)
Hygor luze63a574c767d
diff --git a/docs/topics/stats.rst b/docs/topics/stats.rstindex a74b9824b..40f7a6990 100644--- a/docs/topics/stats.rst+++ b/docs/topics/stats.rst@@ -727,8 +727,8 @@ one per actual value of the placeholder... stat:: robotstxt/request_count``robotstxt/request_count``- Number of ``robots.txt`` files requested, i.e. 1 per network location for- which at least 1 request was sent.+ Number of :file:`robots.txt` files requested, i.e. 1 per scheme and+ network location for which at least 1 request was sent.Set by:class:`~scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware`.diff --git a/scrapy/downloadermiddlewares/robotstxt.py b/scrapy/downloadermiddlewares/robotstxt.pyindex 2ec98df35..5260adf23 100644--- a/scrapy/downloadermiddlewares/robotstxt.py+++ b/scrapy/downloadermiddlewares/robotstxt.py@@ -19,6 +19,7 @@ from scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.defer import maybe_deferred_to_futurefrom scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.misc import build_from_crawler, load_object+from scrapy.utils.url import _originif TYPE_CHECKING:from scrapy import Spider@@ -72,7 +73,11 @@ class RobotsTxtMiddleware:self._robotstxt_useragent: str | None = crawler.settings["ROBOTSTXT_USER_AGENT"]self.crawler: Crawler = crawlerself._stats: StatsCollector = crawler.stats- self._parsers: dict[str, RobotParser | Deferred[RobotParser | None] | None] = {}+ # Keyed by scheme and network location, which identify the robots.txt+ # file that applies to a URL (RFC 9309).+ self._parsers: dict[+ tuple[str, str], RobotParser | Deferred[RobotParser | None] | None+ ] = {}self._parserimpl: type[RobotParser] = load_object(crawler.settings.get("ROBOTSTXT_PARSER"))@@ -111,12 +116,18 @@ class RobotsTxtMiddleware:returnif request.url.startswith("data:") or request.url.startswith("file:"):return- netloc = urlparse_cached(request).netloc- if netloc not in self._parsers and self._is_robotstxt_request(request):+ if "_robotstxt_origin" in request.meta:+ # A redirect or retry of a robots.txt request let through below.+ return+ origin = _origin(request)+ if origin not in self._parsers and self._is_robotstxt_request(request):# Let this request download normally and use its own response as# this host's robots.txt, instead of triggering a second,- # separate download of the same URL.- self._parsers[netloc] = Deferred()+ # separate download of the same URL. The meta key survives+ # redirects and retries, whose final response or exception is the+ # one this middleware gets.+ self._parsers[origin] = Deferred()+ request.meta["_robotstxt_origin"] = originself._stats.inc_value("robotstxt/request_count")returnrp = await self.robot_parser(request)@@ -126,35 +137,21 @@ class RobotsTxtMiddleware:async def process_response(self, request: Request, response: Response, spider: Spider | None = None) -> Response:- netloc = urlparse_cached(request).netloc- parser = self._parsers.get(netloc)- if (- isinstance(parser, Deferred)- and not parser.called- and self._is_robotstxt_request(request)- ):- await self._parse_robots(response, netloc, request)+ origin = request.meta.get("_robotstxt_origin")+ if origin is not None and isinstance(self._parsers.get(origin), Deferred):+ await self._parse_robots(response, origin, request)return response@_warn_spider_argasync def process_exception(self, request: Request, exception: Exception, spider: Spider | None = None) -> None:- netloc = urlparse_cached(request).netloc- parser = self._parsers.get(netloc)- if (- isinstance(parser, Deferred)- and not parser.called- and self._is_robotstxt_request(request)- ):- self._robots_error(exception, netloc, request)+ origin = request.meta.get("_robotstxt_origin")+ if origin is not None and isinstance(self._parsers.get(origin), Deferred):+ self._robots_error(exception, origin, request)@staticmethoddef _is_robotstxt_request(request: Request) -> bool:- # robot_parser() handles its own internal robots.txt request directly,- # without going through process_response()/process_exception().- if request.meta.get("dont_obey_robotstxt"):- return Falseurl = urlparse_cached(request)return request.url == f"{url.scheme}://{url.netloc}/robots.txt"@@ -179,10 +176,10 @@ class RobotsTxtMiddleware:async def robot_parser(self, request: Request) -> RobotParser | None:url = urlparse_cached(request)- netloc = url.netloc+ origin = _origin(request)- if netloc not in self._parsers:- self._parsers[netloc] = Deferred()+ if origin not in self._parsers:+ self._parsers[origin] = Deferred()robotsurl = f"{url.scheme}://{url.netloc}/robots.txt"meta: dict[str, Any] = {"dont_obey_robotstxt": True,@@ -198,12 +195,12 @@ class RobotsTxtMiddleware:)try:resp = await self.crawler.engine.download_async(robotsreq)- await self._parse_robots(resp, netloc, request)+ await self._parse_robots(resp, origin, request)except Exception as e:- self._robots_error(e, netloc, request)+ self._robots_error(e, origin, request)self._stats.inc_value("robotstxt/request_count")- parser = self._parsers[netloc]+ parser = self._parsers[origin]if isinstance(parser, Deferred):# Every caller needs to get its own Deferred, so that awaiting or# cancelling one doesn't affect others.@@ -218,7 +215,7 @@ class RobotsTxtMiddleware:return parserasync def _parse_robots(- self, response: Response, netloc: str, request: Request+ self, response: Response, origin: tuple[str, str], request: Request) -> None:self._stats.inc_value("robotstxt/response_count")self._stats.inc_value(f"robotstxt/response_status_count/{response.status}")@@ -229,12 +226,14 @@ class RobotsTxtMiddleware:request=request,response=response,)- rp_dfd = self._parsers[netloc]+ rp_dfd = self._parsers[origin]assert isinstance(rp_dfd, Deferred)- self._parsers[netloc] = rp+ self._parsers[origin] = rprp_dfd.callback(rp)- def _robots_error(self, exc: Exception, netloc: str, request: Request) -> None:+ def _robots_error(+ self, exc: Exception, origin: tuple[str, str], request: Request+ ) -> None:if not isinstance(exc, IgnoreRequest):logger.error(f"Error downloading {request}",@@ -243,7 +242,7 @@ class RobotsTxtMiddleware:)key = f"robotstxt/exception_count/{type(exc)}"self._stats.inc_value(key)- rp_dfd = self._parsers[netloc]+ rp_dfd = self._parsers[origin]assert isinstance(rp_dfd, Deferred)- self._parsers[netloc] = None+ self._parsers[origin] = Nonerp_dfd.callback(None)diff --git a/scrapy/spiders/sitemap.py b/scrapy/spiders/sitemap.pyindex 647540baa..aadf3245a 100644--- a/scrapy/spiders/sitemap.py+++ b/scrapy/spiders/sitemap.py@@ -20,7 +20,7 @@ from scrapy.utils._compression import (gzip_magic_number,)from scrapy.utils._sitemap import Sitemap, sitemap_urls_from_robots-from scrapy.utils.httpobj import urlparse_cached+from scrapy.utils.url import _originif TYPE_CHECKING:from scrapy.crawler import Crawler@@ -134,19 +134,19 @@ class SitemapSpider(Spider):c = cast("CallbackT", getattr(self, c)) # noqa: PLW2901self._cbs.append((regex(r), c))self._follow: list[re.Pattern[str]] = [regex(x) for x in self.sitemap_follow]- self._robots_sitemaps: dict[str, list[str]] = {}- self._signal_only_netlocs: set[str] = set()+ self._robots_sitemaps: dict[tuple[str, str], list[str]] = {}+ self._signal_only_origins: set[tuple[str, str]] = set()def _robots_parsed(self, robotparser: RobotParser, request: Request, response: Response) -> None:- netloc = urlparse_cached(request).netloc+ origin = _origin(request)urls = [urljoin(request.url, url) for url in robotparser.sitemaps()]- if netloc in self._signal_only_netlocs:+ if origin in self._signal_only_origins:# No request for this host's robots.txt was sent from start(), so# _parse_sitemap() will never run for it; schedule its sitemaps# directly instead of stashing them for a response that never arrives.- self._signal_only_netlocs.discard(netloc)+ self._signal_only_origins.discard(origin)for url in urls:if self._scheme_allowed(url, response.url) and any(x.search(url) for x in self._follow@@ -161,26 +161,24 @@ class SitemapSpider(Spider):))else:- self._robots_sitemaps[netloc] = urls+ self._robots_sitemaps[origin] = urlsasync def start(self) -> AsyncIterator[Any]:- sitemap_netlocs = {- urlparse_cached(url).netloc- for url in self.sitemap_urls- if not url.endswith("/robots.txt")+ sitemap_origins = {+ _origin(url) for url in self.sitemap_urls if not url.endswith("/robots.txt")}for url in self.sitemap_urls:- netloc = urlparse_cached(url).netloc+ origin = _origin(url)if (self._obey_robotstxtand url.endswith("/robots.txt")- and netloc in sitemap_netlocs+ and origin in sitemap_origins):# RobotsTxtMiddleware will fetch and parse this robots.txt# anyway, to check the other sitemap_urls requests to the same# host, so rely on the robots_parsed signal for it instead of# requesting it a second time here.- self._signal_only_netlocs.add(netloc)+ self._signal_only_origins.add(origin)continueyield Request(url, self._parse_sitemap)@@ -280,8 +278,7 @@ class SitemapSpider(Spider):def _parse_sitemap(self, response: Response) -> Iterable[Request]:if response.url.endswith("/robots.txt"):urls = list(sitemap_urls_from_robots(response.body, base_url=response.url))- netloc = urlparse_cached(response).netloc- for url in self._robots_sitemaps.pop(netloc, ()):+ for url in self._robots_sitemaps.pop(_origin(response), ()):if url not in urls:urls.append(url)return (diff --git a/scrapy/utils/url.py b/scrapy/utils/url.pyindex c275878b3..309e7f3d0 100644--- a/scrapy/utils/url.py+++ b/scrapy/utils/url.py@@ -182,6 +182,12 @@ def strip_url()+def _origin(url: str | Request | Response) -> tuple[str, str]:+ """Return the scheme and network location of *url*."""+ parsed_url = urlparse_cached(url)+ return parsed_url.scheme, parsed_url.netloc++def _redirect_url(url: str, location: bytes) -> str:"""Return the absolute URL that the *location* value of the ``Location``header of a response to a request to *url* points to."""diff --git a/tests/test_downloadermiddleware_robotstxt.py b/tests/test_downloadermiddleware_robotstxt.pyindex 821bdcccc..8c1916f1b 100644--- a/tests/test_downloadermiddleware_robotstxt.py+++ b/tests/test_downloadermiddleware_robotstxt.py@@ -271,6 +271,33 @@ Disallow: /some/randome/page.htmlassert "Robotstxt address not found" in caplog.textawait self.assertNotIgnored(Request("http://site.local/allowed"), middleware)+ @pytest.mark.parametrize(+ "follow_up_url",+ ["http://site.local/robots.txt", "https://site.local/robots.txt"],+ )+ @pytest.mark.parametrize("fails", [False, True])+ @coroutine_test+ async def test_robotstxt_request_retried_or_redirected(+ self, follow_up_url: str, fails: bool+ ) -> None:+ self.crawler.settings.set("ROBOTSTXT_OBEY", True)+ middleware = build_from_crawler(RobotsTxtMiddleware, self.crawler)+ request = Request("http://site.local/robots.txt")+ await middleware.process_request(request)+ follow_up = request.replace(url=follow_up_url)+ await self.assertNotIgnored(follow_up, middleware)+ blocked = Request("http://site.local/blocked")+ if fails:+ err = CannotResolveHostError("Robotstxt address not found")+ await middleware.process_exception(follow_up, err)+ await self.assertNotIgnored(blocked, middleware)+ else:+ body = b"User-agent: *\nDisallow: /blocked\n"+ response = TextResponse(follow_up_url, body=body)+ await middleware.process_response(follow_up, response)+ await self.assertIgnored(blocked, middleware)+ assert not self.crawler.engine.download_async.called+@coroutine_testasync def test_robotstxt_process_exception_ignores_unrelated_request(self,@@ -359,6 +386,31 @@ Disallow: /some/randome/page.htmlassert robotsreq.meta["download_handler"] == "named"assert robotsreq.meta["is_robotstxt_request"] is True+ @pytest.mark.parametrize("ignored_first", [False, True])+ @coroutine_test+ async def test_robotstxt_per_scheme(self, ignored_first: bool) -> None:+ allowed_url = "http://site.local/blocked"+ ignored_url = "https://site.local/blocked"+ self.crawler.settings.set("ROBOTSTXT_OBEY", True)+ robots = {+ "http://site.local/robots.txt": b"User-agent: *\nDisallow:\n",+ "https://site.local/robots.txt": b"User-agent: *\nDisallow: /blocked\n",+ }++ async def return_response(request: Request) -> Response:+ return TextResponse(request.url, body=robots[request.url])++ self.crawler.engine.download_async.side_effect = return_response+ middleware = build_from_crawler(RobotsTxtMiddleware, self.crawler)+ if ignored_first:+ await self.assertIgnored(Request(ignored_url), middleware)+ await self.assertNotIgnored(Request(allowed_url), middleware)+ else:+ await self.assertNotIgnored(Request(allowed_url), middleware)+ await self.assertIgnored(Request(ignored_url), middleware)+ calls = self.crawler.engine.download_async.call_args_list+ assert sorted(call[0][0].url for call in calls) == sorted(robots)+async def assertNotIgnored(self, request: Request, middleware: RobotsTxtMiddleware) -> None:diff --git a/tests/test_spider_sitemap.py b/tests/test_spider_sitemap.pyindex 0228a2638..8ebdb8624 100644--- a/tests/test_spider_sitemap.py+++ b/tests/test_spider_sitemap.py@@ -177,6 +177,27 @@ Sitemap: /sitemap-relative-url.xml"http://www.example.com/sitemap-from-parser.xml",]+ def test_get_sitemap_urls_from_robots_parsed_signal_other_scheme(self):+ crawler = get_crawler(self.spider_class, settings_dict={"ROBOTSTXT_OBEY": True})+ spider = self.spider_class.from_crawler(crawler, "example.com")++ class FakeRobotParser:+ def sitemaps(self):+ return ["/sitemap-http.xml"]++ crawler.signals.send_catch_log(+ signal=signals.robots_parsed,+ robotparser=FakeRobotParser(),+ request=Request("http://www.example.com/robots.txt"),+ response=TextResponse("http://www.example.com/robots.txt"),+ )++ robots = b"Sitemap: https://www.example.com/sitemap-https.xml\n"+ r = TextResponse(url="https://www.example.com/robots.txt", body=robots)+ assert [req.url for req in spider._parse_sitemap(r)] == [+ "https://www.example.com/sitemap-https.xml",+ ]+def test_robots_parsed_signal_not_connected_without_robotstxt_obey(self):crawler = get_crawler(self.spider_class)spider = self.spider_class.from_crawler(crawler, "example.com")@@ -203,7 +224,7 @@ Sitemap: /sitemap-relative-url.xmlcrawler = get_crawler(_Spider, settings_dict={"ROBOTSTXT_OBEY": True})spider = _Spider.from_crawler(crawler, "example.com")crawler.engine = mock.MagicMock()- spider._signal_only_netlocs.add("www.example.com")+ spider._signal_only_origins.add(("http", "www.example.com"))class FakeRobotParser:def sitemaps(self):@@ -225,7 +246,7 @@ Sitemap: /sitemap-relative-url.xmlassert scheduled.callback == spider._parse_sitemap # pylint: disable=comparison-with-callableurl = "http://www.example.com/sitemap.xml"assert calls == [(url, {"loc": url}, "robotstxt", robots_response)]- assert spider._signal_only_netlocs == set()+ assert spider._signal_only_origins == set()assert spider._robots_sitemaps == {}def test_sitemap_follow_robots_parsed_signal(self):@@ -235,7 +256,7 @@ Sitemap: /sitemap-relative-url.xmlcrawler = get_crawler(_FollowSpider, settings_dict={"ROBOTSTXT_OBEY": True})spider = _FollowSpider.from_crawler(crawler, "example.com")crawler.engine = mock.MagicMock()- spider._signal_only_netlocs.add("www.example.com")+ spider._signal_only_origins.add(("http", "www.example.com"))class FakeRobotParser:def sitemaps(self):@@ -526,7 +547,27 @@ Sitemap: /sitemap-relative-url.xml"http://www.example.com/sitemap.xml","http://other.example.com/robots.txt",]- assert spider._signal_only_netlocs == {"www.example.com"}+ assert spider._signal_only_origins == {("http", "www.example.com")}++ @coroutine_test+ async def test_start_keeps_robots_url_of_other_scheme(self):+ crawler = get_crawler(self.spider_class, settings_dict={"ROBOTSTXT_OBEY": True})+ spider = self.spider_class.from_crawler(+ crawler,+ "example.com",+ sitemap_urls=[+ "http://www.example.com/sitemap.xml",+ "https://www.example.com/robots.txt",+ ],+ )++ urls = [request.url async for request in spider.start()]++ assert urls == [+ "http://www.example.com/sitemap.xml",+ "https://www.example.com/robots.txt",+ ]+ assert spider._signal_only_origins == set()@coroutine_testasync def test_robots_txt_requested_once_when_other_sitemap_url_goes_first(