Scrapy, a fast high-level web crawling & scraping framework for Python.
Implement a close reason for robots.txt affecting all start requests (#6164)
Adrián Chaves52f7d6a72087
diff --git a/docs/topics/api.rst b/docs/topics/api.rstindex acc09511d..84befb2be 100644--- a/docs/topics/api.rst+++ b/docs/topics/api.rst@@ -92,14 +92,7 @@ to how you :ref:`configure the downloader middlewaresFor an introduction on extensions and a list of available extensions onScrapy see :ref:`topics-extensions`.- .. attribute:: engine-- The execution engine, which coordinates the core crawling logic- between the scheduler, downloader and spiders.-- Some extensions may want to access the Scrapy engine to inspect or- modify the downloader and scheduler behaviour, although this is an- advanced use and this API is not yet stable.+ .. autoattribute:: engine.. attribute:: spider@@ -215,7 +208,7 @@ Engine API==========.. autoclass:: scrapy.core.engine.ExecutionEngine()- :members: needs_backout, running, scheduler, state+ :members: close_spider_async, needs_backout, running, scheduler, state.. autoclass:: scrapy.core.engine.EngineState:members:diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rstindex d952a2232..1304560e4 100644--- a/docs/topics/downloader-middleware.rst+++ b/docs/topics/downloader-middleware.rst@@ -1190,30 +1190,7 @@ See also: :reqmeta:`priority_adjust`.RobotsTxtMiddleware--------------------.. class:: scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware-- This middleware filters out requests forbidden by the robots.txt exclusion- standard.-- To make sure Scrapy respects robots.txt make sure the middleware is enabled- and the :setting:`ROBOTSTXT_OBEY` setting is enabled.-- The :setting:`ROBOTSTXT_USER_AGENT` setting can be used to specify the- user agent string to use for matching in the robots.txt_ file. If it- is ``None``, the User-Agent header you are sending with the request or the- :setting:`USER_AGENT` setting (in that order) will be used for determining- the user agent to use in the robots.txt_ file.-- This middleware has to be combined with a robots.txt_ parser.-- Scrapy ships with support for the following robots.txt_ parsers:-- * :ref:`Protego <protego-parser>` (default)- * :ref:`RobotFileParser <python-robotfileparser>`- * :ref:`Robotexclusionrulesparser <rerp-parser>`-- You can change the robots.txt_ parser with the :setting:`ROBOTSTXT_PARSER`- setting. Or you can also :ref:`implement support for a new parser <support-for-new-robots-parser>`.+.. autoclass:: scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware().. reqmeta:: dont_obey_robotstxtdiff --git a/docs/topics/stats.rst b/docs/topics/stats.rstindex ea80a4872..10bc4a8cd 100644--- a/docs/topics/stats.rst+++ b/docs/topics/stats.rst@@ -318,6 +318,10 @@ one per actual value of the placeholder.- ``memusage_exceeded``: see :setting:`MEMUSAGE_LIMIT_MB`.+ - ``robotstxt_denied``: no :ref:`start request <start-requests>` could be+ crawled, and robots.txt rules denied at least one of them, see+ :class:`~scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware`.+- ``shutdown``: the crawl was interrupted, e.g. by a system signal suchas ``SIGINT`` (:kbd:`Ctrl-C`).diff --git a/scrapy/core/engine.py b/scrapy/core/engine.pyindex 03bf4d175..46b759e7e 100644--- a/scrapy/core/engine.py+++ b/scrapy/core/engine.py@@ -174,6 +174,15 @@ class _Slot:class ExecutionEngine:+ """The execution engine manages all the core :ref:`components+ <topics-components>`, such as the :ref:`scheduler <topics-scheduler>`, the+ downloader, or the :ref:`spider <topics-spiders>`, at run time.++ Some components access the engine through :attr:`Crawler.engine+ <scrapy.crawler.Crawler.engine>` to access or modify other components, or+ use core functionality such as closing the running spider.+ """+_SLOT_HEARTBEAT_INTERVAL: float = 5.0def __init__(@@ -852,17 +861,17 @@ class ExecutionEngine:mode: _StopMode = "graceful",error: bool = False,) -> None:- """Close (cancel) spider and clear all its outstanding requests, and- stop the engine.+ """Stop the crawl with the specified *reason* and clear all its+ outstanding requests... versionadded:: 2.14- *reason* is the spider finish reason (see the :stat:`finish_reason`- stat). *error* is a flag that specifies whether the crawl should be- considered failed (see the :stat:`finish_reason_error` stat). If- *mode* is ``"graceful"``, this method will wait until the requests- that are already in the downloader are downloaded and processed; if- it's ``"fast"`` they will be dropped.+ *reason* is an arbitrary string; see :stat:`finish_reason` for the+ reasons that built-in components use. *error* is a flag that specifies+ whether the crawl should be considered failed (see the+ :stat:`finish_reason_error` stat). If *mode* is ``"graceful"``, this+ method will wait until the requests that are already in the downloader+ are downloaded and processed; if it's ``"fast"`` they will be dropped.If the spider was not opened before, this method raises:exc:`RuntimeError`.diff --git a/scrapy/crawler.py b/scrapy/crawler.pyindex 66ac0e642..fd75fba9a 100644--- a/scrapy/crawler.py+++ b/scrapy/crawler.py@@ -114,6 +114,13 @@ class _LateAttribute(Generic[_T]):class Crawler:engine: _LateAttribute[ExecutionEngine] = _LateAttribute()+ """The execution engine, which coordinates the core crawling logic between+ the scheduler, downloader and spiders.++ Some extensions may want to access the Scrapy engine to inspect or modify+ the downloader and scheduler behaviour, although this is an advanced use+ and this API is not yet stable.+ """extensions: _LateAttribute[ExtensionManager] = _LateAttribute()logformatter: _LateAttribute[LogFormatter] = _LateAttribute()"""The log formatter of this crawler.diff --git a/scrapy/downloadermiddlewares/robotstxt.py b/scrapy/downloadermiddlewares/robotstxt.pyindex 210d52586..454958868 100644--- a/scrapy/downloadermiddlewares/robotstxt.py+++ b/scrapy/downloadermiddlewares/robotstxt.py@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Any, Selffrom twisted.internet.defer import Deferredfrom scrapy import signals-from scrapy.exceptions import IgnoreRequest, NotConfigured+from scrapy.exceptions import CloseSpider, IgnoreRequest, NotConfiguredfrom scrapy.http import Request, Responsefrom scrapy.http.request import NO_CALLBACKfrom scrapy.utils.decorators import _warn_spider_arg@@ -31,11 +31,43 @@ logger = logging.getLogger(__name__)class RobotsTxtMiddleware:+ """This middleware filters out requests forbidden by the robots.txt+ exclusion standard.++ To make sure Scrapy respects robots.txt make sure the middleware is enabled+ and the :setting:`ROBOTSTXT_OBEY` setting is enabled.++ The :setting:`ROBOTSTXT_USER_AGENT` setting can be used to specify the+ user agent string to use for matching in the robots.txt_ file. If it+ is ``None``, the User-Agent header you are sending with the request or the+ :setting:`USER_AGENT` setting (in that order) will be used for determining+ the user agent to use in the robots.txt_ file.++ This middleware has to be combined with a robots.txt_ parser.++ Scrapy ships with support for the following robots.txt_ parsers:++ * :ref:`Protego <protego-parser>` (default)+ * :ref:`RobotFileParser <python-robotfileparser>`+ * :ref:`Robotexclusionrulesparser <rerp-parser>`++ You can change the robots.txt_ parser with the :setting:`ROBOTSTXT_PARSER`+ setting. Or you can also :ref:`implement support for a new parser+ <support-for-new-robots-parser>`.++ If no :ref:`start request <start-requests>` can be crawled, and robots.txt+ rules denied at least one of them, the crawl stops with the+ ``robotstxt_denied`` :stat:`finish_reason`, as long as+ :class:`~scrapy.spidermiddlewares.start.StartSpiderMiddleware` is enabled.+ """+DOWNLOAD_PRIORITY: int = 1000def __init__(self, crawler: Crawler):if not crawler.settings.getbool("ROBOTSTXT_OBEY"):raise NotConfigured+ self._start_request_crawled = False+ self._start_request_denied = Falseself._default_useragent: str = crawler.settings["USER_AGENT"]self._robotstxt_useragent: str | None = crawler.settings["ROBOTSTXT_USER_AGENT"]self.crawler: Crawler = crawler@@ -48,10 +80,29 @@ class RobotsTxtMiddleware:# check if parser dependencies are met, this should throw an error otherwise.build_from_crawler(self._parserimpl, self.crawler, b"")+ crawler.signals.connect(+ self._response_received, signal=signals.response_received+ )+ crawler.signals.connect(self._spider_idle, signal=signals.spider_idle)+@classmethoddef from_crawler(cls, crawler: Crawler) -> Self:return cls(crawler)+ def _response_received(self, request: Request) -> None:+ if request.meta.get("is_start_request"):+ self._start_request_crawled = True++ def _spider_idle(self) -> None:+ if self._start_request_crawled or not self._start_request_denied:+ return+ logger.error(+ "Stopping the crawl: no start request could be crawled, and at "+ "least one of them was rejected based on robots.txt rules. See "+ "https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#topics-dlmw-robots"+ )+ raise CloseSpider("robotstxt_denied")+@_warn_spider_argasync def process_request(self, request: Request, spider: Spider | None = None@@ -78,6 +129,8 @@ class RobotsTxtMiddleware:extra={"spider": self.crawler.spider},)self._stats.inc_value("robotstxt/forbidden")+ if request.meta.get("is_start_request"):+ self._start_request_denied = Trueraise IgnoreRequest("Forbidden by robots.txt")async def robot_parser(self, request: Request) -> RobotParser | None:diff --git a/tests/mockserver/http.py b/tests/mockserver/http.pyindex 9f37af048..2753be720 100644--- a/tests/mockserver/http.py+++ b/tests/mockserver/http.py@@ -81,6 +81,9 @@ class Root(BaseResource):b"enc-gb18030",Data(b"<p>gb18030 encoding</p>", "text/html; charset=gb18030"),)+ put_child(+ self, b"robots.txt", Data(b"User-agent: *\nDisallow: /deny\n", "text/plain")+ )put_child(self, b"redirect", Redirect(b"/redirected"))put_child(self, b"redirect-no-meta-refresh", NoMetaRefreshRedirect(b"/redirected")diff --git a/tests/test_downloadermiddleware_robotstxt.py b/tests/test_downloadermiddleware_robotstxt.pyindex 62b91e9f4..f385b73e4 100644--- a/tests/test_downloadermiddleware_robotstxt.py+++ b/tests/test_downloadermiddleware_robotstxt.py@@ -1,13 +1,14 @@from __future__ import annotationsimport asyncio+from typing import TYPE_CHECKING, Anyfrom unittest import mockimport pytestfrom twisted.internet.defer import Deferred, DeferredListfrom twisted.python import failure-from scrapy import signals+from scrapy import Spider, signalsfrom scrapy.downloadermiddlewares.robotstxt import RobotsTxtMiddlewarefrom scrapy.exceptions import CannotResolveHostError, IgnoreRequest, NotConfiguredfrom scrapy.http import Request, Response, TextResponse@@ -16,9 +17,15 @@ from scrapy.settings import Settingsfrom scrapy.utils.asyncio import call_laterfrom scrapy.utils.defer import deferred_from_coro, maybe_deferred_to_futurefrom scrapy.utils.misc import build_from_crawler+from scrapy.utils.test import get_crawlerfrom tests.utils.decorators import coroutine_testfrom tests.utils.robotstxt import rerp_available+if TYPE_CHECKING:+ from collections.abc import Iterable++ from tests.mockserver.http import MockServer+class TestRobotsTxtMiddleware:def setup_method(self) -> None:@@ -307,6 +314,81 @@ Disallow: /some/randome/page.htmlassert request.callback == NO_CALLBACK+class _IgnoreSpider(Spider):+ name = "test"++ def parse(self, response: Response) -> None:+ pass+++class _FollowSpider(Spider):+ name = "test"++ def parse(self, response: Response) -> Iterable[Request]:+ yield response.follow("/deny/a")+++class TestRobotsTxtDeniedCloseReason:+ @staticmethod+ async def _finish_reason(+ spider_cls: type[Spider], settings: dict[str, Any] | None = None, **kwargs: Any+ ) -> Any:+ crawler = get_crawler(+ spider_cls, settings_dict={"ROBOTSTXT_OBEY": True, **(settings or {})}+ )+ await crawler.crawl_async(**kwargs)+ assert crawler.stats+ return crawler.stats.get_value("finish_reason")++ @coroutine_test+ async def test_all_denied(self, mockserver: MockServer) -> None:+ reason = await self._finish_reason(+ _IgnoreSpider,+ start_urls=[mockserver.url("/deny/a"), mockserver.url("/deny/b")],+ )+ assert reason == "robotstxt_denied"++ @coroutine_test+ async def test_all_denied_low_concurrency(self, mockserver: MockServer) -> None:+ reason = await self._finish_reason(+ _IgnoreSpider,+ settings={"CONCURRENT_REQUESTS": 1},+ start_urls=[mockserver.url("/deny/a"), mockserver.url("/deny/b")],+ )+ assert reason == "robotstxt_denied"++ @coroutine_test+ async def test_all_denied_after_redirect(self, mockserver: MockServer) -> None:+ reason = await self._finish_reason(+ _IgnoreSpider, start_urls=[mockserver.url("/redirect-to?goto=/deny/a")]+ )+ assert reason == "robotstxt_denied"++ @coroutine_test+ async def test_denied_and_download_failure(self, mockserver: MockServer) -> None:+ reason = await self._finish_reason(+ _IgnoreSpider,+ settings={"RETRY_ENABLED": False},+ start_urls=[mockserver.url("/deny/a"), mockserver.url("/drop")],+ )+ assert reason == "robotstxt_denied"++ @coroutine_test+ async def test_some_denied(self, mockserver: MockServer) -> None:+ reason = await self._finish_reason(+ _IgnoreSpider,+ start_urls=[mockserver.url("/deny/a"), mockserver.url("/text")],+ )+ assert reason == "finished"++ @coroutine_test+ async def test_denied_follow_up_request(self, mockserver: MockServer) -> None:+ reason = await self._finish_reason(+ _FollowSpider, start_urls=[mockserver.url("/text")]+ )+ assert reason == "finished"++@pytest.mark.skipif(not rerp_available(), reason="Rerp parser is not installed")class TestRobotsTxtMiddlewareWithRerp(TestRobotsTxtMiddleware):def setup_method(self):