Scrapy, a fast high-level web crawling & scraping framework for Python.
Bump the minimum Python version for Ruff. (#8262)
Andrey Rakhmatullin9def81fd06d0
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 8e6942b55..97feaa9b1 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -6,7 +6,7 @@ exclude: |)repos:- repo: https://github.com/astral-sh/ruff-pre-commit- rev: v0.16.8+ rev: v0.16.9hooks:- id: ruff-checkargs: [ --fix ]diff --git a/pyproject.toml b/pyproject.tomlindex c22bf3400..dca1f2513 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -339,10 +339,6 @@ filterwarnings = ["ignore:Coverage disabled via --no-cov switch!",]-[tool.ruff]-# TODO-target-version = "py310"-[tool.ruff.lint]extend-select = [# flake8-builtinsdiff --git a/scrapy/core/downloader/contextfactory.py b/scrapy/core/downloader/contextfactory.pyindex 5732a9351..66f7ffef2 100644--- a/scrapy/core/downloader/contextfactory.py+++ b/scrapy/core/downloader/contextfactory.py@@ -1,7 +1,7 @@from __future__ import annotationsimport warnings-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Self, castfrom formerly import deprecated_classfrom OpenSSL import SSL@@ -34,9 +34,6 @@ from scrapy.utils.misc import build_from_crawler, load_objectif TYPE_CHECKING:from twisted.internet._sslverify import ClientTLSOptions- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.settings import BaseSettingsdiff --git a/scrapy/core/downloader/handlers/_aiohttp.py b/scrapy/core/downloader/handlers/_aiohttp.pyindex d2cad2b19..679bfcbad 100644--- a/scrapy/core/downloader/handlers/_aiohttp.py+++ b/scrapy/core/downloader/handlers/_aiohttp.py@@ -1,6 +1,5 @@from __future__ import annotations-import asyncioimport ipaddressimport sslfrom contextlib import asynccontextmanager@@ -78,7 +77,9 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):@asynccontextmanagerasync def _make_request(- self, request: Request, timeout: float+ self,+ request: Request,+ timeout: float, # noqa: ASYNC109) -> AsyncIterator[_ClientResponse]:proxy = self._extract_proxy_url_with_creds(request)headers = self._request_headers(request).to_tuple_list()@@ -99,7 +100,7 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):proxy=proxy,) as response:yield cast("_ClientResponse", response)- except (TimeoutError, asyncio.TimeoutError) as e:+ except TimeoutError as e:raise DownloadTimeoutError(f"Getting {request.url} took longer than {timeout} seconds.") from ediff --git a/scrapy/core/downloader/handlers/_base_streaming.py b/scrapy/core/downloader/handlers/_base_streaming.pyindex c7f4c82d8..cd9f4cbd7 100644--- a/scrapy/core/downloader/handlers/_base_streaming.py+++ b/scrapy/core/downloader/handlers/_base_streaming.py@@ -5,7 +5,16 @@ import loggingimport timefrom abc import ABC, abstractmethodfrom io import BytesIO-from typing import TYPE_CHECKING, Any, ClassVar, Generic, NoReturn, TypedDict, TypeVar+from typing import (+ TYPE_CHECKING,+ Any,+ ClassVar,+ Generic,+ NoReturn,+ NotRequired,+ TypedDict,+ TypeVar,+)from urllib.parse import quote, urlsplitfrom scrapy import Request, signals@@ -34,9 +43,6 @@ if TYPE_CHECKING:from _typeshed import SizedBuffer- # typing.NotRequired requires Python 3.11- from typing_extensions import NotRequired-from scrapy.crawler import Crawlerfrom scrapy.http import Headers, Responsediff --git a/scrapy/core/downloader/handlers/_httpx.py b/scrapy/core/downloader/handlers/_httpx.pyindex 7b1917bf6..3102d1bcd 100644--- a/scrapy/core/downloader/handlers/_httpx.py+++ b/scrapy/core/downloader/handlers/_httpx.py@@ -148,7 +148,9 @@ class HttpxDownloadHandler(_Base):@asynccontextmanagerasync def _make_request(- self, request: Request, timeout: float+ self,+ request: Request,+ timeout: float, # noqa: ASYNC109) -> AsyncIterator[httpx.Response]:proxy = self._extract_proxy_url_with_creds(request)if proxy and proxy.startswith("socks") and not HAS_SOCKS: # pragma: no coverdiff --git a/scrapy/core/downloader/handlers/base.py b/scrapy/core/downloader/handlers/base.pyindex 999c003b4..148b272a3 100644--- a/scrapy/core/downloader/handlers/base.py+++ b/scrapy/core/downloader/handlers/base.py@@ -1,12 +1,9 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selfif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Requestfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex 37b27c8a6..48a0e8d80 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -9,7 +9,7 @@ from contextlib import suppressfrom functools import partialfrom io import BytesIOfrom time import monotonic-from typing import TYPE_CHECKING, Any, TypedDict, TypeVar, cast+from typing import TYPE_CHECKING, Any, NotRequired, TypedDict, TypeVar, castfrom urllib.parse import urldefrag, urlparsefrom twisted.internet import ssl@@ -71,9 +71,6 @@ if TYPE_CHECKING:from twisted.internet.interfaces import IAddress, IConsumerfrom twisted.web._newclient import Request as TxRequest- # typing.NotRequired requires Python 3.11- from typing_extensions import NotRequired-from scrapy.crawler import Crawlerdiff --git a/scrapy/core/scheduler.py b/scrapy/core/scheduler.pyindex 17279977f..7866ca831 100644--- a/scrapy/core/scheduler.py+++ b/scrapy/core/scheduler.py@@ -4,7 +4,7 @@ import jsonimport loggingfrom abc import abstractmethodfrom pathlib import Path-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Self, cast# working around https://github.com/sphinx-doc/sphinx/issues/10400from twisted.internet.defer import Deferred # noqa: TC002@@ -16,9 +16,6 @@ from scrapy.utils.misc import build_from_crawler, load_objectif TYPE_CHECKING:from queuelib.queue import BaseQueue- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.dupefilters import BaseDupeFilterfrom scrapy.http.request import Requestdiff --git a/scrapy/downloadermiddlewares/cookies.py b/scrapy/downloadermiddlewares/cookies.pyindex 3461c8943..1ab48a35e 100644--- a/scrapy/downloadermiddlewares/cookies.py+++ b/scrapy/downloadermiddlewares/cookies.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport loggingfrom collections import defaultdict-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom tldextract import TLDExtract@@ -18,9 +18,6 @@ if TYPE_CHECKING:from collections.abc import Iterable, Sequencefrom http.cookiejar import Cookie- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Request, Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http.request import VerboseCookiediff --git a/scrapy/downloadermiddlewares/defaultheaders.py b/scrapy/downloadermiddlewares/defaultheaders.pyindex 7c940a078..d363c2b16 100644--- a/scrapy/downloadermiddlewares/defaultheaders.py+++ b/scrapy/downloadermiddlewares/defaultheaders.py@@ -6,7 +6,7 @@ See documentation in docs/topics/downloader-middleware.rstfrom __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.python import without_none_values@@ -14,9 +14,6 @@ from scrapy.utils.python import without_none_valuesif TYPE_CHECKING:from collections.abc import Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Request, Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/downloadtimeout.py b/scrapy/downloadermiddlewares/downloadtimeout.pyindex bccfb230c..91fbb64d0 100644--- a/scrapy/downloadermiddlewares/downloadtimeout.py+++ b/scrapy/downloadermiddlewares/downloadtimeout.py@@ -6,16 +6,13 @@ See documentation in docs/topics/downloader-middleware.rstfrom __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Request, Spider, signalsfrom scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.deprecate import warn_on_deprecated_spider_attributeif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/httpauth.py b/scrapy/downloadermiddlewares/httpauth.pyindex b09abdadd..b3c769c6a 100644--- a/scrapy/downloadermiddlewares/httpauth.py+++ b/scrapy/downloadermiddlewares/httpauth.py@@ -7,7 +7,7 @@ See documentation in docs/topics/downloader-middleware.rstfrom __future__ import annotationsimport warnings-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom w3lib.http import basic_auth_header@@ -18,9 +18,6 @@ from scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.url import url_is_from_any_domainif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/httpcache.py b/scrapy/downloadermiddlewares/httpcache.pyindex bfc6e66ea..998c6b812 100644--- a/scrapy/downloadermiddlewares/httpcache.py+++ b/scrapy/downloadermiddlewares/httpcache.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport loggingfrom email.utils import formatdate-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom twisted.internet.error import ConnectError, ConnectionDone, ConnectionLost@@ -18,9 +18,6 @@ from scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.misc import load_objectif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http.request import Requestfrom scrapy.http.response import Responsediff --git a/scrapy/downloadermiddlewares/httpcompression.py b/scrapy/downloadermiddlewares/httpcompression.pyindex f01c8a1f9..52f3f4ff1 100644--- a/scrapy/downloadermiddlewares/httpcompression.py+++ b/scrapy/downloadermiddlewares/httpcompression.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport warningsfrom itertools import chainfrom logging import getLogger-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom scrapy import Request, Spider, signalsfrom scrapy.exceptions import (@@ -26,9 +26,6 @@ from scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.deprecate import warn_on_deprecated_spider_attributeif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollectordiff --git a/scrapy/downloadermiddlewares/httpproxy.py b/scrapy/downloadermiddlewares/httpproxy.pyindex e034dced1..faae041a1 100644--- a/scrapy/downloadermiddlewares/httpproxy.py+++ b/scrapy/downloadermiddlewares/httpproxy.py@@ -1,7 +1,7 @@from __future__ import annotationsimport base64-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom urllib.parse import unquote, urlunparsefrom urllib.request import ( # type: ignore[attr-defined]_parse_proxy,@@ -15,9 +15,6 @@ from scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.python import to_bytesif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Request, Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/jsonvalidation.py b/scrapy/downloadermiddlewares/jsonvalidation.pyindex 748a4625b..cd32114ec 100644--- a/scrapy/downloadermiddlewares/jsonvalidation.py+++ b/scrapy/downloadermiddlewares/jsonvalidation.py@@ -1,14 +1,11 @@from __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy.exceptions import NotConfiguredfrom scrapy.http import JsonResponseif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Requestfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/offsite.py b/scrapy/downloadermiddlewares/offsite.pyindex b9a26df3a..bac64b04a 100644--- a/scrapy/downloadermiddlewares/offsite.py+++ b/scrapy/downloadermiddlewares/offsite.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport loggingimport re-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Request, Spider, signalsfrom scrapy.exceptions import IgnoreRequest@@ -10,9 +10,6 @@ from scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.httpobj import urlparse_cachedif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollectordiff --git a/scrapy/downloadermiddlewares/redirect.py b/scrapy/downloadermiddlewares/redirect.pyindex 3fb958f1d..49f1fa3e8 100644--- a/scrapy/downloadermiddlewares/redirect.py+++ b/scrapy/downloadermiddlewares/redirect.py@@ -1,7 +1,7 @@from __future__ import annotationsimport logging-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Self, castfrom urllib.parse import urljoin, urlparsefrom w3lib.url import safe_url_string@@ -16,9 +16,6 @@ from scrapy.utils.python import global_object_namefrom scrapy.utils.response import get_meta_refreshif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Request, Spiderfrom scrapy.crawler import Crawlerfrom scrapy.settings import BaseSettingsdiff --git a/scrapy/downloadermiddlewares/retry.py b/scrapy/downloadermiddlewares/retry.pyindex b8eed4da9..28126a4d4 100644--- a/scrapy/downloadermiddlewares/retry.py+++ b/scrapy/downloadermiddlewares/retry.py@@ -10,7 +10,7 @@ RETRY_HTTP_CODES - which HTTP response codes to retryfrom __future__ import annotationsfrom logging import Logger, getLevelName, getLogger-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy.exceptions import NotConfiguredfrom scrapy.utils.decorators import _warn_spider_arg@@ -19,9 +19,6 @@ from scrapy.utils.python import global_object_namefrom scrapy.utils.response import response_status_messageif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-import scrapyfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/robotstxt.py b/scrapy/downloadermiddlewares/robotstxt.pyindex 2d73c3b48..38659024e 100644--- a/scrapy/downloadermiddlewares/robotstxt.py+++ b/scrapy/downloadermiddlewares/robotstxt.py@@ -7,7 +7,7 @@ enable this middleware and enable the ROBOTSTXT_OBEY setting.from __future__ import annotationsimport logging-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom twisted.internet.defer import Deferred@@ -21,9 +21,6 @@ from scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.misc import build_from_crawler, load_objectif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Spiderfrom scrapy.crawler import Crawlerfrom scrapy.robotstxt import RobotParserdiff --git a/scrapy/downloadermiddlewares/stats.py b/scrapy/downloadermiddlewares/stats.pyindex 07de1c2e7..267f9ca77 100644--- a/scrapy/downloadermiddlewares/stats.py+++ b/scrapy/downloadermiddlewares/stats.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom twisted.web import http@@ -10,9 +10,6 @@ from scrapy.utils.python import global_object_name, to_bytesfrom scrapy.utils.request import request_httpreprif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Request, Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/downloadermiddlewares/useragent.py b/scrapy/downloadermiddlewares/useragent.pyindex 61f84b518..bea025dac 100644--- a/scrapy/downloadermiddlewares/useragent.py+++ b/scrapy/downloadermiddlewares/useragent.py@@ -2,16 +2,13 @@from __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Request, Spider, signalsfrom scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.deprecate import warn_on_deprecated_spider_attributeif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/dupefilters.py b/scrapy/dupefilters.pyindex 098394b9e..53e557846 100644--- a/scrapy/dupefilters.py+++ b/scrapy/dupefilters.py@@ -5,7 +5,7 @@ import sqlite3from pathlib import Pathfrom shutil import rmtreefrom tempfile import mkdtemp-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom warnings import warnfrom scrapy.exceptions import ScrapyDeprecationWarning@@ -22,9 +22,6 @@ if TYPE_CHECKING:from twisted.internet.defer import Deferred- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http.request import Requestfrom scrapy.spiders import Spiderdiff --git a/scrapy/extensions/closespider.py b/scrapy/extensions/closespider.pyindex 3ae2858ac..34f16e52a 100644--- a/scrapy/extensions/closespider.py+++ b/scrapy/extensions/closespider.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport loggingfrom collections import defaultdict-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom scrapy import Request, Spider, signalsfrom scrapy.exceptions import NotConfigured@@ -24,9 +24,6 @@ if TYPE_CHECKING:from twisted.internet.task import LoopingCallfrom twisted.python.failure import Failure- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/extensions/corestats.py b/scrapy/extensions/corestats.pyindex 3c92b713a..f1a4b6ddf 100644--- a/scrapy/extensions/corestats.py+++ b/scrapy/extensions/corestats.py@@ -4,16 +4,13 @@ Extension for collecting core stats like items scraped and start/finish timesfrom __future__ import annotations-from datetime import datetime, timezone+from datetime import UTC, datetimefrom time import monotonic-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom scrapy import Spider, signalsif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollector@@ -35,14 +32,14 @@ class CoreStats:return odef spider_opened(self, spider: Spider) -> None:- self.start_time = datetime.now(tz=timezone.utc)+ self.start_time = datetime.now(tz=UTC)self._start_time_mono = monotonic()self.stats.set_value("start_time", self.start_time)def spider_closed(self, spider: Spider, reason: str, error: bool = False) -> None:assert self.start_time is not Noneassert self._start_time_mono is not None- finish_time, finish_time_mono = datetime.now(tz=timezone.utc), monotonic()+ finish_time, finish_time_mono = datetime.now(tz=UTC), monotonic()elapsed_time_seconds = finish_time_mono - self._start_time_monoself.stats.set_value("elapsed_time_seconds", elapsed_time_seconds)self.stats.set_value("finish_time", finish_time)diff --git a/scrapy/extensions/debug.py b/scrapy/extensions/debug.pyindex 8802a3b58..9efada546 100644--- a/scrapy/extensions/debug.py+++ b/scrapy/extensions/debug.py@@ -13,7 +13,7 @@ import sysimport threadingimport tracebackfrom pdb import Pdb-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy.utils.engine import format_engine_statusfrom scrapy.utils.trackref import format_live_refs@@ -21,9 +21,6 @@ from scrapy.utils.trackref import format_live_refsif TYPE_CHECKING:from types import FrameType- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerdiff --git a/scrapy/extensions/feedexport.py b/scrapy/extensions/feedexport.pyindex a501fa711..73d2c9ca6 100644--- a/scrapy/extensions/feedexport.py+++ b/scrapy/extensions/feedexport.py@@ -14,10 +14,10 @@ import sysimport warningsfrom abc import ABC, abstractmethodfrom collections.abc import Callable, Iterable-from datetime import datetime, timezone+from datetime import UTC, datetimefrom pathlib import Path, PureWindowsPathfrom tempfile import NamedTemporaryFile-from typing import IO, TYPE_CHECKING, Any, Protocol, TypeAlias, cast+from typing import IO, TYPE_CHECKING, Any, Protocol, Self, TypeAlias, castfrom urllib.parse import unquote, urlparsefrom uuid import uuid4@@ -39,9 +39,6 @@ from scrapy.utils.python import without_none_valuesif TYPE_CHECKING:from _typeshed import OpenBinaryMode- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.exporters import BaseItemExporterfrom scrapy.settings import BaseSettings, Settings@@ -814,7 +811,7 @@ class FeedExporter:slot: FeedSlot | None = None,) -> dict[str, Any]:params = {k: getattr(spider, k) for k in dir(spider)}- utc_now = datetime.now(tz=timezone.utc)+ utc_now = datetime.now(tz=UTC)params["time"] = utc_now.replace(microsecond=0).isoformat().replace(":", "-")params["batch_time"] = utc_now.isoformat().replace(":", "-")params["batch_id"] = slot.batch_id + 1 if slot is not None else 1diff --git a/scrapy/extensions/httpcache.py b/scrapy/extensions/httpcache.pyindex 8e885d8d0..bf93ff46b 100644--- a/scrapy/extensions/httpcache.py+++ b/scrapy/extensions/httpcache.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport gzipimport loggingimport pickle-from datetime import timezone+from datetime import UTCfrom email.utils import parsedate_to_datetimefrom importlib import import_modulefrom pathlib import Path@@ -429,7 +429,7 @@ def rfc1123_to_epoch(date_str: str | bytes | None) -> int | None:date_str = to_unicode(date_str, encoding="ascii")date = parsedate_to_datetime(date_str)if date.tzinfo is None:- date = date.replace(tzinfo=timezone.utc)+ date = date.replace(tzinfo=UTC)return int(date.timestamp())except Exception:return Nonediff --git a/scrapy/extensions/logcount.py b/scrapy/extensions/logcount.pyindex fcce64438..daf3b9dbd 100644--- a/scrapy/extensions/logcount.py+++ b/scrapy/extensions/logcount.py@@ -1,15 +1,12 @@from __future__ import annotationsimport logging-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Spider, signalsfrom scrapy.utils.log import LogCounterHandlerif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerdiff --git a/scrapy/extensions/logstats.py b/scrapy/extensions/logstats.pyindex 08eb584ce..fbb3e83a9 100644--- a/scrapy/extensions/logstats.py+++ b/scrapy/extensions/logstats.py@@ -1,7 +1,7 @@from __future__ import annotationsimport logging-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Spider, signalsfrom scrapy.exceptions import NotConfigured@@ -10,9 +10,6 @@ from scrapy.utils.asyncio import AsyncioLoopingCall, create_looping_callif TYPE_CHECKING:from twisted.internet.task import LoopingCall- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollectordiff --git a/scrapy/extensions/memdebug.py b/scrapy/extensions/memdebug.pyindex 35ff90e3b..1490d7646 100644--- a/scrapy/extensions/memdebug.py+++ b/scrapy/extensions/memdebug.py@@ -7,16 +7,13 @@ See documentation in docs/topics/extensions.rstfrom __future__ import annotationsimport gc-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Spider, signalsfrom scrapy.exceptions import NotConfiguredfrom scrapy.utils.trackref import live_refsif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollectordiff --git a/scrapy/extensions/memusage.py b/scrapy/extensions/memusage.pyindex 3e54065ff..59126893d 100644--- a/scrapy/extensions/memusage.py+++ b/scrapy/extensions/memusage.py@@ -12,7 +12,7 @@ import sysimport warningsfrom importlib import import_modulefrom pprint import pformat-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import signalsfrom scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning@@ -24,9 +24,6 @@ from scrapy.utils.misc import build_from_crawlerif TYPE_CHECKING:from twisted.internet.task import LoopingCall- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollectordiff --git a/scrapy/extensions/periodic_log.py b/scrapy/extensions/periodic_log.pyindex 86eb1eae5..79211469f 100644--- a/scrapy/extensions/periodic_log.py+++ b/scrapy/extensions/periodic_log.py@@ -2,8 +2,8 @@ from __future__ import annotationsimport loggingimport warnings-from datetime import datetime, timezone-from typing import TYPE_CHECKING, Any+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any, Selffrom scrapy import Spider, signalsfrom scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning@@ -16,9 +16,6 @@ if TYPE_CHECKING:from twisted.internet.task import LoopingCall- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollector@@ -121,7 +118,7 @@ class PeriodicLog:return odef spider_opened(self, spider: Spider) -> None:- self.time_prev: datetime = datetime.now(tz=timezone.utc)+ self.time_prev: datetime = datetime.now(tz=UTC)self.delta_prev: dict[str, int | float] = {}self.stats_prev: dict[str, int | float] = {}@@ -150,7 +147,7 @@ class PeriodicLog:return {"delta": delta}def log_timing(self) -> dict[str, Any]:- now = datetime.now(tz=timezone.utc)+ now = datetime.now(tz=UTC)time = {"log_interval": self.interval,"start_time": self.stats._stats["start_time"],diff --git a/scrapy/extensions/remote_control.py b/scrapy/extensions/remote_control.pyindex cc06d5815..d8d648790 100644--- a/scrapy/extensions/remote_control.py+++ b/scrapy/extensions/remote_control.py@@ -12,7 +12,7 @@ import secretsimport timeimport tracebackfrom types import CodeType-from typing import TYPE_CHECKING, Any, Literal, cast+from typing import TYPE_CHECKING, Any, Literal, Self, castfrom aiohttp import web@@ -32,9 +32,6 @@ if TYPE_CHECKING:from datetime import datetimefrom pathlib import Path- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerlogger = logging.getLogger(__name__)@@ -269,7 +266,7 @@ class RemoteControl:and hmac.compare_digest(token, self._auth_token))- async def _run_code(self, code_obj: CodeType, timeout: float) -> ExecuteResult:+ async def _run_code(self, code_obj: CodeType, timeout: float) -> ExecuteResult: # noqa: ASYNC109"""Run a compiled code object with a timeout and capture its output."""buf = io.StringIO()ns = self._make_namespace(buf)@@ -283,7 +280,7 @@ class RemoteControl:if inspect.iscoroutine(eval_result):try:await asyncio.wait_for(eval_result, timeout)- except asyncio.TimeoutError:+ except TimeoutError:# wait_for cancelled the coroutine at an await point.status = "timeout"except Exception:diff --git a/scrapy/extensions/spiderstate.py b/scrapy/extensions/spiderstate.pyindex 3166834dc..e7cb23e87 100644--- a/scrapy/extensions/spiderstate.py+++ b/scrapy/extensions/spiderstate.py@@ -2,16 +2,13 @@ from __future__ import annotationsimport picklefrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Spider, signalsfrom scrapy.exceptions import NotConfiguredfrom scrapy.utils.conf import _job_dirif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerdiff --git a/scrapy/extensions/statsmailer.py b/scrapy/extensions/statsmailer.pyindex 3dc38dded..f612cf519 100644--- a/scrapy/extensions/statsmailer.py+++ b/scrapy/extensions/statsmailer.py@@ -7,7 +7,7 @@ Use STATSMAILER_RCPTS setting to enable and give the recipient mail addressfrom __future__ import annotationsimport warnings-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Spider, signalsfrom scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning@@ -17,9 +17,6 @@ from scrapy.utils.misc import build_from_crawlerif TYPE_CHECKING:from twisted.internet.defer import Deferred- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.statscollectors import StatsCollectordiff --git a/scrapy/extensions/telnet.py b/scrapy/extensions/telnet.pyindex a9a391843..0ffa10e8a 100644--- a/scrapy/extensions/telnet.py+++ b/scrapy/extensions/telnet.py@@ -9,7 +9,7 @@ from __future__ import annotationsimport loggingimport pprintfrom secrets import token_hex-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom twisted.conch import telnetfrom twisted.conch.insults import insults@@ -25,9 +25,6 @@ from scrapy.utils.trackref import print_live_refsif TYPE_CHECKING:from twisted.internet.tcp import Port- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerdiff --git a/scrapy/extensions/throttle.py b/scrapy/extensions/throttle.pyindex f44aee03d..e6532457e 100644--- a/scrapy/extensions/throttle.py+++ b/scrapy/extensions/throttle.py@@ -1,15 +1,12 @@from __future__ import annotationsimport logging-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy import Request, Spider, signalsfrom scrapy.exceptions import NotConfiguredif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.core.downloader import Slotfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/http/cookies.py b/scrapy/http/cookies.pyindex 533d8d17f..e446b9d16 100644--- a/scrapy/http/cookies.py+++ b/scrapy/http/cookies.py@@ -4,7 +4,7 @@ import reimport timefrom http.cookiejar import Cookie, CookiePolicy, DefaultCookiePolicyfrom http.cookiejar import CookieJar as _CookieJar-from typing import TYPE_CHECKING, cast+from typing import TYPE_CHECKING, Self, castfrom scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.python import to_unicode@@ -12,9 +12,6 @@ from scrapy.utils.python import to_unicodeif TYPE_CHECKING:from collections.abc import Iterator, Sequence- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Requestfrom scrapy.http import Responsediff --git a/scrapy/http/headers.py b/scrapy/http/headers.pyindex 762c0e6cd..7bb126cb1 100644--- a/scrapy/http/headers.py+++ b/scrapy/http/headers.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport warningsfrom collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeAlias, cast+from typing import TYPE_CHECKING, Any, Self, TypeAlias, castfrom w3lib.http import headers_dict_to_raw@@ -13,9 +13,6 @@ from scrapy.utils.python import to_unicodeif TYPE_CHECKING:from collections.abc import Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-_RawValue: TypeAlias = bytes | str | intdiff --git a/scrapy/http/request/__init__.py b/scrapy/http/request/__init__.pyindex d3c575468..05ed8955b 100644--- a/scrapy/http/request/__init__.py+++ b/scrapy/http/request/__init__.py@@ -13,6 +13,8 @@ from typing import (Any,Concatenate,NoReturn,+ NotRequired,+ Self,TypeAlias,TypedDict,TypeVar,@@ -33,9 +35,6 @@ if TYPE_CHECKING:from twisted.python.failure import Failure- # typing.NotRequired and typing.Self require Python 3.11- from typing_extensions import NotRequired, Self-# circular importfrom scrapy.http import Responsediff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.pyindex 12745292b..dbb78f9cf 100644--- a/scrapy/http/request/form.py+++ b/scrapy/http/request/form.py@@ -8,7 +8,7 @@ See documentation in docs/topics/request-response.rstfrom __future__ import annotationsfrom collections.abc import Iterable, Mapping-from typing import TYPE_CHECKING, Any, ClassVar, TypeAlias, cast+from typing import TYPE_CHECKING, Any, ClassVar, Self, TypeAlias, castfrom urllib.parse import urlencode, urljoin, urlsplit, urlunsplitfrom warnings import warn@@ -20,7 +20,6 @@ from scrapy.http.request import Requestfrom scrapy.utils.python import is_listlike, to_bytesif TYPE_CHECKING:- # typing.Self requires Python 3.11from lxml.html import (FormElement,InputElement,@@ -28,7 +27,6 @@ if TYPE_CHECKING:SelectElement,TextareaElement,)- from typing_extensions import Selffrom scrapy.http.response.text import TextResponsediff --git a/scrapy/http/request/json_request.py b/scrapy/http/request/json_request.pyindex 13fee06d8..6fa6d9976 100644--- a/scrapy/http/request/json_request.py+++ b/scrapy/http/request/json_request.py@@ -10,14 +10,10 @@ from __future__ import annotationsimport copyimport jsonimport warnings-from typing import TYPE_CHECKING, Any, overload+from typing import Any, Self, overloadfrom scrapy.http.request import Request, RequestTypeVar-if TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-class JsonRequest(Request):__slots__ = ("_dumps_kwargs",)diff --git a/scrapy/http/response/__init__.py b/scrapy/http/response/__init__.pyindex 0dffe4aa2..b8bd858f5 100644--- a/scrapy/http/response/__init__.py+++ b/scrapy/http/response/__init__.py@@ -7,7 +7,7 @@ See documentation in docs/topics/request-response.rstfrom __future__ import annotations-from typing import TYPE_CHECKING, Any, TypeVar, overload+from typing import TYPE_CHECKING, Any, Self, TypeVar, overloadfrom urllib.parse import urljoinfrom scrapy.exceptions import NotSupported@@ -22,9 +22,6 @@ if TYPE_CHECKING:from twisted.python.failure import Failure- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.http.request import CallbackT, CookiesTfrom scrapy.selector import SelectorListdiff --git a/scrapy/item.py b/scrapy/item.pyindex 347f88581..89c712f1b 100644--- a/scrapy/item.py+++ b/scrapy/item.py@@ -10,16 +10,13 @@ from abc import ABCMetafrom collections.abc import MutableMappingfrom copy import deepcopyfrom pprint import pformat-from typing import TYPE_CHECKING, Any, NoReturn+from typing import TYPE_CHECKING, Any, NoReturn, Selffrom scrapy.utils.trackref import object_refif TYPE_CHECKING:from collections.abc import Iterator, KeysView- # typing.Self requires Python 3.11- from typing_extensions import Self-class Field(dict[str, Any]):"""Container of field metadata"""diff --git a/scrapy/logformatter.py b/scrapy/logformatter.pyindex bfb2d5dff..89ad48e24 100644--- a/scrapy/logformatter.py+++ b/scrapy/logformatter.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport loggingimport os-from typing import TYPE_CHECKING, Any, TypedDict+from typing import TYPE_CHECKING, Any, Self, TypedDictfrom twisted.python.failure import Failure@@ -13,9 +13,6 @@ from scrapy.utils.python import global_object_namefrom scrapy.utils.request import referer_strif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerdiff --git a/scrapy/mail.py b/scrapy/mail.pyindex 0691312a3..de94906a9 100644--- a/scrapy/mail.py+++ b/scrapy/mail.py@@ -15,7 +15,7 @@ from email.mime.nonmultipart import MIMENonMultipartfrom email.mime.text import MIMETextfrom email.utils import formatdatefrom io import BytesIO-from typing import IO, TYPE_CHECKING, Any+from typing import IO, TYPE_CHECKING, Any, Selffrom twisted.internet import sslfrom twisted.internet.defer import Deferred@@ -32,9 +32,6 @@ if TYPE_CHECKING:from twisted.mail.smtp import ESMTPSenderFactoryfrom twisted.python.failure import Failure- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerdiff --git a/scrapy/middleware.py b/scrapy/middleware.pyindex c7ffb5980..95134a58c 100644--- a/scrapy/middleware.py+++ b/scrapy/middleware.py@@ -5,7 +5,7 @@ import pprintimport warningsfrom abc import ABC, abstractmethodfrom collections import defaultdict, deque-from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, cast+from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, Self, TypeVar, castfrom scrapy.exceptions import NotConfigured, ScrapyDeprecationWarningfrom scrapy.utils.defer import ensure_awaitable@@ -18,9 +18,6 @@ if TYPE_CHECKING:from twisted.internet.defer import Deferred- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Spiderfrom scrapy.crawler import Crawlerfrom scrapy.settings import Settingsdiff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.pyindex d0fd32777..7bf230ae0 100644--- a/scrapy/pipelines/files.py+++ b/scrapy/pipelines/files.py@@ -15,11 +15,21 @@ import timeimport warningsfrom collections import defaultdictfrom contextlib import suppress-from datetime import datetime, timezone+from datetime import UTC, datetimefrom ftplib import FTPfrom io import BytesIOfrom pathlib import Path-from typing import IO, TYPE_CHECKING, Any, ClassVar, NoReturn, Protocol, TypedDict, cast+from typing import (+ IO,+ TYPE_CHECKING,+ Any,+ ClassVar,+ NoReturn,+ Protocol,+ Self,+ TypedDict,+ cast,+)from urllib.parse import urlparsefrom itemadapter import ItemAdapter@@ -51,9 +61,6 @@ if TYPE_CHECKING:from twisted.python.failure import Failure- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.settings import BaseSettings@@ -432,7 +439,7 @@ class FTPFilesStore:time_format = "%Y%m%d%H%M%S.%f" if "." in modified else "%Y%m%d%H%M%S"last_modified = (datetime.strptime(modified, time_format)- .replace(tzinfo=timezone.utc)+ .replace(tzinfo=UTC).timestamp())m = hashlib.md5() # noqa: S324diff --git a/scrapy/pipelines/images.py b/scrapy/pipelines/images.pyindex 931d066f5..370ef1a9f 100644--- a/scrapy/pipelines/images.py+++ b/scrapy/pipelines/images.py@@ -11,7 +11,7 @@ import hashlibimport warningsfrom contextlib import suppressfrom io import BytesIO-from typing import TYPE_CHECKING, Any, ClassVar, cast+from typing import TYPE_CHECKING, Any, ClassVar, Self, castfrom itemadapter import ItemAdapter@@ -29,9 +29,6 @@ if TYPE_CHECKING:from PIL import Image- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.pipelines.media import FileInfoOrError, MediaPipelinefrom scrapy.settings import BaseSettingsdiff --git a/scrapy/pipelines/media.py b/scrapy/pipelines/media.pyindex 58cc21246..2b0f81ecd 100644--- a/scrapy/pipelines/media.py+++ b/scrapy/pipelines/media.py@@ -6,7 +6,7 @@ import loggingimport warningsfrom abc import ABC, abstractmethodfrom collections import OrderedDict, defaultdict-from typing import TYPE_CHECKING, Any, Literal, TypeAlias, TypedDict, cast+from typing import TYPE_CHECKING, Any, Literal, Self, TypeAlias, TypedDict, castfrom twisted.internet.defer import Deferred, DeferredListfrom twisted.python.failure import Failure@@ -30,9 +30,6 @@ from scrapy.utils.python import global_object_nameif TYPE_CHECKING:from collections.abc import Awaitable, Callable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/pqueues.py b/scrapy/pqueues.pyindex bee338e2b..5771d9ce1 100644--- a/scrapy/pqueues.py+++ b/scrapy/pqueues.py@@ -4,16 +4,13 @@ import hashlibimport loggingfrom contextlib import suppressfrom pathlib import Path-from typing import TYPE_CHECKING, Protocol, cast+from typing import TYPE_CHECKING, Protocol, Self, castfrom scrapy.utils.misc import build_from_crawlerif TYPE_CHECKING:from collections.abc import Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Requestfrom scrapy.core.downloader import Downloaderfrom scrapy.crawler import Crawlerdiff --git a/scrapy/resolver.py b/scrapy/resolver.pyindex 861a5b2b5..6865eb463 100644--- a/scrapy/resolver.py+++ b/scrapy/resolver.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selfimport attrfrom twisted.internet import defer@@ -21,9 +21,6 @@ if TYPE_CHECKING:from twisted.internet.defer import Deferred- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawler# TODO: cache missesdiff --git a/scrapy/robotstxt.py b/scrapy/robotstxt.pyindex a9e2f5563..d980f2004 100644--- a/scrapy/robotstxt.py+++ b/scrapy/robotstxt.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport loggingimport sysfrom abc import ABCMeta, abstractmethod-from typing import TYPE_CHECKING, cast+from typing import TYPE_CHECKING, Self, castfrom urllib.robotparser import RobotFileParserfrom protego import Protego@@ -11,9 +11,6 @@ from protego import Protegofrom scrapy.utils.python import to_unicodeif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Spiderfrom scrapy.crawler import Crawlerdiff --git a/scrapy/settings/__init__.py b/scrapy/settings/__init__.pyindex 9662000ef..b52ec429a 100644--- a/scrapy/settings/__init__.py+++ b/scrapy/settings/__init__.py@@ -7,7 +7,7 @@ from collections.abc import Iterable, Iterator, Mapping, MutableMappingfrom importlib import import_modulefrom logging import getLoggerfrom pprint import pformat-from typing import TYPE_CHECKING, Any, TypeAlias, cast+from typing import TYPE_CHECKING, Any, Self, TypeAlias, castfrom scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.settings import default_settings@@ -16,15 +16,13 @@ from scrapy.utils.python import global_object_namelogger = getLogger(__name__)+if TYPE_CHECKING:from types import ModuleType# https://github.com/python/typing/issues/445#issuecomment-1131458824from _typeshed import SupportsItems- # typing.Self requires Python 3.11- from typing_extensions import Self-_SettingsInput: TypeAlias = (SupportsItems[str, Any] | Iterable[tuple[str, Any]] | str | None)diff --git a/scrapy/spiderloader.py b/scrapy/spiderloader.pyindex 244b7338f..034cb4f81 100644--- a/scrapy/spiderloader.py+++ b/scrapy/spiderloader.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport tracebackimport warningsfrom collections import defaultdict-from typing import TYPE_CHECKING, Protocol, cast+from typing import TYPE_CHECKING, Protocol, Self, cast# working around https://github.com/sphinx-doc/sphinx/issues/10400from scrapy import Request, Spider # noqa: TC001@@ -13,9 +13,6 @@ from scrapy.utils.spider import iter_spider_classesif TYPE_CHECKING:from types import ModuleType- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.settings import BaseSettingsdiff --git a/scrapy/spidermiddlewares/base.py b/scrapy/spidermiddlewares/base.pyindex 3b14d2b0a..d2e9c72ee 100644--- a/scrapy/spidermiddlewares/base.py+++ b/scrapy/spidermiddlewares/base.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom scrapy import Request, Spiderfrom scrapy.utils.decorators import _warn_spider_arg@@ -8,9 +8,6 @@ from scrapy.utils.decorators import _warn_spider_argif TYPE_CHECKING:from collections.abc import AsyncIterator, Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/spidermiddlewares/depth.py b/scrapy/spidermiddlewares/depth.pyindex 83d242f82..3794c523d 100644--- a/scrapy/spidermiddlewares/depth.py+++ b/scrapy/spidermiddlewares/depth.py@@ -7,7 +7,7 @@ See documentation in docs/topics/spider-middleware.rstfrom __future__ import annotationsimport logging-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom scrapy.spidermiddlewares.base import BaseSpiderMiddlewarefrom scrapy.utils.decorators import _warn_spider_arg@@ -15,9 +15,6 @@ from scrapy.utils.decorators import _warn_spider_argif TYPE_CHECKING:from collections.abc import AsyncIterator, Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http import Request, Responsediff --git a/scrapy/spidermiddlewares/httperror.py b/scrapy/spidermiddlewares/httperror.pyindex ed5d09b52..94a480344 100644--- a/scrapy/spidermiddlewares/httperror.py+++ b/scrapy/spidermiddlewares/httperror.py@@ -7,7 +7,7 @@ See documentation in docs/topics/spider-middleware.rstfrom __future__ import annotationsimport logging-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom scrapy.exceptions import IgnoreRequestfrom scrapy.utils.decorators import _warn_spider_arg@@ -15,9 +15,6 @@ from scrapy.utils.decorators import _warn_spider_argif TYPE_CHECKING:from collections.abc import Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Spiderfrom scrapy.crawler import Crawlerfrom scrapy.http import Responsediff --git a/scrapy/spidermiddlewares/referer.py b/scrapy/spidermiddlewares/referer.pyindex 1305874d5..399b221d0 100644--- a/scrapy/spidermiddlewares/referer.py+++ b/scrapy/spidermiddlewares/referer.py@@ -7,7 +7,7 @@ from __future__ import annotationsimport warningsfrom abc import ABC, abstractmethod-from typing import TYPE_CHECKING, cast+from typing import TYPE_CHECKING, Self, TypedDict, Unpack, castfrom urllib.parse import urlparsefrom warnings import warn@@ -19,9 +19,6 @@ from scrapy.utils.python import _looks_like_import_path, to_unicodefrom scrapy.utils.url import strip_urlif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self, TypedDict, Unpack-from scrapy.crawler import Crawlerfrom scrapy.settings import BaseSettingsdiff --git a/scrapy/spidermiddlewares/stickymeta.py b/scrapy/spidermiddlewares/stickymeta.pyindex 72d7c5752..a0a43f35e 100644--- a/scrapy/spidermiddlewares/stickymeta.py+++ b/scrapy/spidermiddlewares/stickymeta.py@@ -1,14 +1,11 @@from __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy.exceptions import NotConfiguredfrom scrapy.spidermiddlewares.base import BaseSpiderMiddlewareif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Request, Responsediff --git a/scrapy/spidermiddlewares/urllength.py b/scrapy/spidermiddlewares/urllength.pyindex 86bdd2ed6..fb0670521 100644--- a/scrapy/spidermiddlewares/urllength.py+++ b/scrapy/spidermiddlewares/urllength.py@@ -7,15 +7,12 @@ See documentation in docs/topics/spider-middleware.rstfrom __future__ import annotationsimport logging-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom scrapy.exceptions import NotConfiguredfrom scrapy.spidermiddlewares.base import BaseSpiderMiddlewareif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http import Request, Responsediff --git a/scrapy/spiders/__init__.py b/scrapy/spiders/__init__.pyindex d16cc8e40..6a098c6e5 100644--- a/scrapy/spiders/__init__.py+++ b/scrapy/spiders/__init__.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport loggingimport warnings-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Self, castfrom scrapy import signalsfrom scrapy.exceptions import ScrapyDeprecationWarning@@ -21,9 +21,6 @@ if TYPE_CHECKING:from twisted.internet.defer import Deferred- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http.request import CallbackTfrom scrapy.settings import BaseSettingsdiff --git a/scrapy/spiders/crawl.py b/scrapy/spiders/crawl.pyindex 27f3bcae6..e6e0716bc 100644--- a/scrapy/spiders/crawl.py+++ b/scrapy/spiders/crawl.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport copyimport warningsfrom collections.abc import AsyncIterator, Awaitable, Callable-from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar, cast+from typing import TYPE_CHECKING, Any, Self, TypeAlias, TypeVar, castfrom scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.http import HtmlResponse, Request, Response@@ -27,9 +27,6 @@ if TYPE_CHECKING:from twisted.python.failure import Failure- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http.request import CallbackTdiff --git a/scrapy/spiders/sitemap.py b/scrapy/spiders/sitemap.pyindex 6382112ae..972450083 100644--- a/scrapy/spiders/sitemap.py+++ b/scrapy/spiders/sitemap.py@@ -5,7 +5,7 @@ import re# Iterable is needed at the run time for the SitemapSpider._parse_sitemap() annotationfrom collections.abc import AsyncIterator, Iterable, Sequence # noqa: TC003-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Self, castfrom urllib.parse import urljoinfrom scrapy.http import Request, Response, XmlResponse@@ -18,9 +18,6 @@ from scrapy.utils._compression import (from scrapy.utils._sitemap import Sitemap, sitemap_urls_from_robotsif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http.request import CallbackTdiff --git a/scrapy/squeues.py b/scrapy/squeues.pyindex ed3287d1f..4890b2125 100644--- a/scrapy/squeues.py+++ b/scrapy/squeues.py@@ -7,7 +7,7 @@ from __future__ import annotationsimport marshalimport picklefrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom queuelib import queue@@ -17,9 +17,6 @@ if TYPE_CHECKING:from collections.abc import Callablefrom os import PathLike- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy import Requestfrom scrapy.crawler import Crawlerdiff --git a/scrapy/utils/_remote_control.py b/scrapy/utils/_remote_control.pyindex c8423802c..dea23b4ad 100644--- a/scrapy/utils/_remote_control.py+++ b/scrapy/utils/_remote_control.py@@ -7,14 +7,11 @@ import osimport timeimport uuidfrom pathlib import Path-from typing import TYPE_CHECKING, Literal, TypedDict+from typing import TYPE_CHECKING, Literal, NotRequired, TypedDictfrom platformdirs import user_state_dirif TYPE_CHECKING:- # typing.NotRequired requires Python 3.11- from typing_extensions import NotRequired-from scrapy.settings import BaseSettingslogger = logging.getLogger(__name__)diff --git a/scrapy/utils/asyncio.py b/scrapy/utils/asyncio.pyindex b65523f66..a7f372482 100644--- a/scrapy/utils/asyncio.py+++ b/scrapy/utils/asyncio.py@@ -6,7 +6,17 @@ import asyncioimport loggingimport timefrom collections.abc import AsyncIterator, Callable, Coroutine, Iterable-from typing import TYPE_CHECKING, Any, Concatenate, Generic, ParamSpec, TypeVar+from typing import (+ TYPE_CHECKING,+ Any,+ Concatenate,+ Generic,+ ParamSpec,+ Self,+ TypeVar,+ TypeVarTuple,+ Unpack,+)from twisted.internet.defer import Deferredfrom twisted.internet.task import LoopingCall, deferLater@@ -18,14 +28,10 @@ from scrapy.utils.reactor import _is_asyncio_reactor_installed, is_reactor_instaif TYPE_CHECKING:from twisted.internet.base import DelayedCall- # typing.Self, typing.TypeVarTuple and typing.Unpack require Python 3.11- from typing_extensions import Self, TypeVarTuple, Unpack-- _Ts = TypeVarTuple("_Ts")-_T = TypeVar("_T")_P = ParamSpec("_P")+_Ts = TypeVarTuple("_Ts")logger = logging.getLogger(__name__)@@ -236,7 +242,7 @@ def create_looping_call(def call_later(- delay: float, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]+ delay: float, func: Callable[[Unpack[_Ts]], object], *args: *_Ts) -> CallLaterResult:"""Schedule a function to be called after a delay.diff --git a/scrapy/utils/datatypes.py b/scrapy/utils/datatypes.pyindex b6fbe3adf..f5f97cd88 100644--- a/scrapy/utils/datatypes.py+++ b/scrapy/utils/datatypes.py@@ -9,14 +9,11 @@ import collectionsimport contextlibimport weakreffrom collections import OrderedDict-from typing import TYPE_CHECKING, Any, TypeVar, cast+from typing import TYPE_CHECKING, Any, Self, TypeVar, castif TYPE_CHECKING:from collections.abc import Container- # typing.Self requires Python 3.11- from typing_extensions import Self-_KT = TypeVar("_KT")_VT = TypeVar("_VT")diff --git a/scrapy/utils/python.py b/scrapy/utils/python.pyindex 42be078c6..e2d627781 100644--- a/scrapy/utils/python.py+++ b/scrapy/utils/python.py@@ -13,7 +13,7 @@ import weakreffrom collections.abc import AsyncIterator, Iterable, Mappingfrom functools import partial, wrapsfrom itertools import chain-from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, overload+from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, Self, TypeVar, overloadfrom scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.utils.asyncgen import as_async_generator@@ -22,9 +22,6 @@ if TYPE_CHECKING:from collections.abc import Callable, Iteratorfrom re import Pattern- # typing.Self requires Python 3.11- from typing_extensions import Self-_T = TypeVar("_T")_KT = TypeVar("_KT")diff --git a/scrapy/utils/request.py b/scrapy/utils/request.pyindex 24db88b49..53242176c 100644--- a/scrapy/utils/request.py+++ b/scrapy/utils/request.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport hashlibimport jsonimport logging-from typing import TYPE_CHECKING, Any, Protocol+from typing import TYPE_CHECKING, Any, Protocol, Selffrom urllib.parse import urlunparsefrom weakref import WeakKeyDictionary@@ -22,9 +22,6 @@ from scrapy.utils.python import to_bytes, to_unicodeif TYPE_CHECKING:from collections.abc import Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawlerfrom scrapy.http.request import CookiesT, VerboseCookiediff --git a/scrapy/utils/trackref.py b/scrapy/utils/trackref.pyindex b7bd5c017..25cc7909a 100644--- a/scrapy/utils/trackref.py+++ b/scrapy/utils/trackref.py@@ -17,15 +17,12 @@ from __future__ import annotationsfrom operator import itemgetterfrom time import monotonic_nsfrom types import NoneType-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom weakref import WeakKeyDictionaryif TYPE_CHECKING:from collections.abc import Iterable- # typing.Self requires Python 3.11- from typing_extensions import Self-live_refs: WeakKeyDictionary[type, WeakKeyDictionary[object, float]] = (WeakKeyDictionary()diff --git a/tests/keys/__init__.py b/tests/keys/__init__.pyindex 804c9b6a8..c5afff7f1 100644--- a/tests/keys/__init__.py+++ b/tests/keys/__init__.py@@ -1,4 +1,4 @@-from datetime import datetime, timedelta, timezone+from datetime import UTC, datetime, timedeltafrom ipaddress import IPv4Addressfrom pathlib import Path@@ -52,8 +52,8 @@ def generate_keys():.issuer_name(issuer).public_key(key.public_key()).serial_number(random_serial_number())- .not_valid_before(datetime.now(tz=timezone.utc))- .not_valid_after(datetime.now(tz=timezone.utc) + timedelta(days=10))+ .not_valid_before(datetime.now(tz=UTC))+ .not_valid_after(datetime.now(tz=UTC) + timedelta(days=10)).add_extension(SubjectAlternativeName([DNSName("localhost"), IPAddress(IPv4Address("127.0.0.1"))]diff --git a/tests/mockserver/dns.py b/tests/mockserver/dns.pyindex 2af018c66..a3d507d70 100644--- a/tests/mockserver/dns.py+++ b/tests/mockserver/dns.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport sysfrom subprocess import PIPE, Popen-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom twisted.internet import deferfrom twisted.names import dns, error@@ -16,9 +16,6 @@ if TYPE_CHECKING:from twisted.internet.defer import Deferred- # typing.Self requires Python 3.11- from typing_extensions import Self-_Answers = tuple[list[dns.RRHeader], list[dns.RRHeader], list[dns.RRHeader]]diff --git a/tests/mockserver/ftp.py b/tests/mockserver/ftp.pyindex d88e953a7..d09bf6115 100644--- a/tests/mockserver/ftp.py+++ b/tests/mockserver/ftp.py@@ -7,7 +7,7 @@ from pathlib import Pathfrom shutil import rmtreefrom subprocess import PIPE, Popenfrom tempfile import mkdtemp-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom pyftpdlib.authorizers import DummyAuthorizerfrom pyftpdlib.handlers import FTPHandler, TLS_FTPHandler@@ -18,9 +18,6 @@ from tests.utils import get_script_run_envif TYPE_CHECKING:from types import TracebackType- # typing.Self requires Python 3.11- from typing_extensions import Self-class MockFTPServer:"""Creates an FTP server on a random port with a default passwordless userdiff --git a/tests/mockserver/http_base.py b/tests/mockserver/http_base.pyindex 5bc1252d6..dafa71329 100644--- a/tests/mockserver/http_base.py+++ b/tests/mockserver/http_base.py@@ -6,7 +6,7 @@ import argparseimport sysfrom abc import ABC, abstractmethodfrom subprocess import PIPE, Popen-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Selffrom urllib.parse import urlparsefrom twisted.web.server import Site@@ -21,9 +21,6 @@ if TYPE_CHECKING:from twisted.web import resource- # typing.Self requires Python 3.11- from typing_extensions import Self-class BaseMockServer(ABC):listen_http: bool = Truediff --git a/tests/spiders.py b/tests/spiders.pyindex 86329066b..883bde68b 100644--- a/tests/spiders.py+++ b/tests/spiders.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport asyncioimport time-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom urllib.parse import urlencodefrom twisted.internet import defer@@ -26,7 +26,6 @@ if TYPE_CHECKING:from collections.abc import AsyncIterator, Callable, Iteratorfrom twisted.python.failure import Failure- from typing_extensions import Selffrom scrapy.crawler import Crawlerfrom scrapy.http import Headers, Responsediff --git a/tests/test_exporters.py b/tests/test_exporters.pyindex d74556236..7adced8bd 100644--- a/tests/test_exporters.py+++ b/tests/test_exporters.py@@ -5,7 +5,7 @@ import pickleimport refrom abc import ABC, abstractmethodfrom collections.abc import Mapping-from datetime import datetime, timezone+from datetime import UTC, datetimefrom io import BytesIOfrom typing import Any@@ -80,7 +80,7 @@ class TestBaseItemExporter(ABC):return {"boolean": False,"number": 22,- "time": datetime(2015, 1, 1, 1, 1, 1, tzinfo=timezone.utc),+ "time": datetime(2015, 1, 1, 1, 1, 1, tzinfo=UTC),"float": 3.14,}diff --git a/tests/test_extension_periodic_log.py b/tests/test_extension_periodic_log.pyindex 6d4e6a4fc..d084f4a77 100644--- a/tests/test_extension_periodic_log.py+++ b/tests/test_extension_periodic_log.py@@ -23,7 +23,7 @@ stats_dump_1 = {"log_count/INFO": 10,"log_count/WARNING": 1,"start_time": datetime.datetime(- 2023, 6, 16, 8, 59, 18, 993170, tzinfo=datetime.timezone.utc+ 2023, 6, 16, 8, 59, 18, 993170, tzinfo=datetime.UTC),"scheduler/enqueued/memory": 190,"scheduler/enqueued": 190,@@ -46,7 +46,7 @@ stats_dump_2 = {"log_count/INFO": 12,"log_count/WARNING": 1,"start_time": datetime.datetime(- 2023, 6, 16, 8, 59, 18, 993170, tzinfo=datetime.timezone.utc+ 2023, 6, 16, 8, 59, 18, 993170, tzinfo=datetime.UTC),"scheduler/enqueued/memory": 337,"scheduler/enqueued": 337,diff --git a/tests/test_extension_remote_control.py b/tests/test_extension_remote_control.pyindex 5c0cad507..de03f19a3 100644--- a/tests/test_extension_remote_control.py+++ b/tests/test_extension_remote_control.py@@ -6,7 +6,7 @@ import jsonimport loggingimport osfrom contextlib import asynccontextmanager-from datetime import datetime, timezone+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -442,7 +442,7 @@ def test_get_status_project_unset() -> None:def test_get_status_start_time() -> None:extension = _get_extension()- start_time = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)+ start_time = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)extension._crawler.stats.set_value("start_time", start_time)assert extension._get_status()["start_time"] == start_time.timestamp()@@ -451,7 +451,7 @@ def test_get_status_start_time() -> None:async def test_status(tmp_path: Path) -> None:async with _started_extension(tmp_path) as extension:extension._crawler.stats.set_value(- "start_time", datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)+ "start_time", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC))status, body = await _request_status(extension, headers=_auth(extension))assert status == 200@@ -460,7 +460,7 @@ async def test_status(tmp_path: Path) -> None:"spider": extension._crawler.spidercls.name,"project": "scrapybot","scrapy_version": scrapy.__version__,- "start_time": datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc).timestamp(),+ "start_time": datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC).timestamp(),}diff --git a/tests/test_logstats.py b/tests/test_logstats.pyindex 92e88e03f..4484688b2 100644--- a/tests/test_logstats.py+++ b/tests/test_logstats.py@@ -1,6 +1,6 @@from __future__ import annotations-from datetime import datetime, timezone+from datetime import UTC, datetimefrom typing import TYPE_CHECKINGimport pytest@@ -65,12 +65,8 @@ async def test_stats_calculations(crawler: Crawler, stats: StatsCollector) -> Noassert logstats.itemsprev == 3492# Simulate when spider closes after running for 30 mins- stats.set_value(- "start_time", datetime.fromtimestamp(1655100172).astimezone(timezone.utc)- )- stats.set_value(- "finish_time", datetime.fromtimestamp(1655101972).astimezone(timezone.utc)- )+ stats.set_value("start_time", datetime.fromtimestamp(1655100172).astimezone(UTC))+ stats.set_value("finish_time", datetime.fromtimestamp(1655101972).astimezone(UTC))logstats.spider_closed(crawler.spider, "test reason")assert stats.get_value("responses_per_minute") == 172.9assert stats.get_value("items_per_minute") == 116.4@@ -92,12 +88,8 @@ def test_stats_calculation_no_elapsed_time() -> None:"""The stat values should be None since the elapsed time is 0."""logstats = build_from_crawler(LogStats, crawler)- stats.set_value(- "start_time", datetime.fromtimestamp(1655100172).astimezone(timezone.utc)- )- stats.set_value(- "finish_time", datetime.fromtimestamp(1655100172).astimezone(timezone.utc)- )+ stats.set_value("start_time", datetime.fromtimestamp(1655100172).astimezone(UTC))+ stats.set_value("finish_time", datetime.fromtimestamp(1655100172).astimezone(UTC))assert crawler.spiderlogstats.spider_closed(crawler.spider, "test reason")assert stats.get_value("responses_per_minute") is Nonediff --git a/tests/test_robotstxt_interface.py b/tests/test_robotstxt_interface.pyindex 92bba1b85..e4898f8fd 100644--- a/tests/test_robotstxt_interface.py+++ b/tests/test_robotstxt_interface.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import TYPE_CHECKING, cast+from typing import TYPE_CHECKING, Self, castimport pytest@@ -16,9 +16,6 @@ from scrapy.utils.misc import build_from_crawlerfrom tests.utils.robotstxt import rerp_availableif TYPE_CHECKING:- # typing.Self requires Python 3.11- from typing_extensions import Self-from scrapy.crawler import Crawler# The parser backends only use the crawler to get the spider to log with.diff --git a/tests/test_spider_sitemap.py b/tests/test_spider_sitemap.pyindex 0072d9f28..879e987b3 100644--- a/tests/test_spider_sitemap.py+++ b/tests/test_spider_sitemap.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport gzipimport re-from datetime import datetime, timezone+from datetime import UTC, datetimefrom io import BytesIOfrom logging import WARNINGfrom pathlib import Path@@ -183,7 +183,7 @@ Sitemap: /sitemap-relative-url.xmldef sitemap_filter(self, entries):for entry in entries:date_time = datetime.strptime(entry["lastmod"], "%Y-%m-%d").replace(- tzinfo=timezone.utc+ tzinfo=UTC)if date_time.year > 2008:yield entry@@ -255,7 +255,7 @@ Sitemap: /sitemap-relative-url.xmlfor entry in entries:date_time = datetime.strptime(entry["lastmod"].split("T")[0], "%Y-%m-%d"- ).replace(tzinfo=timezone.utc)+ ).replace(tzinfo=UTC)if date_time.year > 2004:yield entrydiff --git a/tests/test_spiderstate.py b/tests/test_spiderstate.pyindex 71258f2a3..55e47d326 100644--- a/tests/test_spiderstate.py+++ b/tests/test_spiderstate.py@@ -1,6 +1,6 @@from __future__ import annotations-from datetime import datetime, timezone+from datetime import UTC, datetimefrom typing import TYPE_CHECKINGimport pytest@@ -19,7 +19,7 @@ def test_store_load(tmp_path: Path) -> None:jobdir = str(tmp_path)spider = Spider(name="default")- dt = datetime.now(tz=timezone.utc)+ dt = datetime.now(tz=UTC)ss = SpiderState(jobdir)ss.spider_opened(spider)diff --git a/tests/test_stats.py b/tests/test_stats.pyindex 3cc9b2186..640d2828f 100644--- a/tests/test_stats.py+++ b/tests/test_stats.py@@ -1,6 +1,6 @@from __future__ import annotations-from datetime import datetime, timezone+from datetime import UTC, datetimefrom typing import TYPE_CHECKINGfrom unittest import mock@@ -39,7 +39,7 @@ class TestCoreStatsExtension:crawler: Crawler,spider: Spider,) -> None:- fixed_datetime = datetime(2019, 12, 1, 11, 38, tzinfo=timezone.utc)+ fixed_datetime = datetime(2019, 12, 1, 11, 38, tzinfo=UTC)mock_datetime.now = mock.Mock(return_value=fixed_datetime)crawler.stats = StatsCollector(crawler)ext = build_from_crawler(CoreStats, crawler)diff --git a/tests/test_utils_defer.py b/tests/test_utils_defer.pyindex 0e8daeb1b..140b5be80 100644--- a/tests/test_utils_defer.py+++ b/tests/test_utils_defer.py@@ -5,7 +5,7 @@ import randomimport socketimport warningsfrom asyncio import Future-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Selffrom unittest import mockimport pytest@@ -35,7 +35,6 @@ if TYPE_CHECKING:from collections.abc import AsyncGenerator, Awaitable, Callable, Generatorfrom twisted.python.failure import Failure- from typing_extensions import Self@pytest.mark.requires_reactor # mustbe_deferred() requires a reactordiff --git a/tests/test_utils_serialize.py b/tests/test_utils_serialize.pyindex b04e87f3e..abb733f1f 100644--- a/tests/test_utils_serialize.py+++ b/tests/test_utils_serialize.py@@ -22,7 +22,7 @@ class TestJsonEncoder:dt_naive = datetime.datetime(2010, 1, 2, 10, 11, 12) # noqa: DTZ001dt_naives = "2010-01-02T10:11:12"dt_aware = datetime.datetime(- 2010, 1, 2, 10, 11, 12, 133700, tzinfo=datetime.timezone.utc+ 2010, 1, 2, 10, 11, 12, 133700, tzinfo=datetime.UTC)dt_awares = "2010-01-02T10:11:12.133700+00:00"d = datetime.date(2010, 1, 2)