Scrapy, a fast high-level web crawling & scraping framework for Python.
Simplifications after dropping Python 3.10, bump tools (#8263)
Andrey Rakhmatullin54783efe7472
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex b0b466aa6..11d17720c 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -119,6 +119,6 @@ jobs:if: endsWith(github.ref_name, '.0')needs:- publish- uses: ./.github/workflows/upgrade-ci-pins.yml+ uses: $/.github/workflows/upgrade-ci-pins.ymlsecrets:CI_PINS_APP_PRIVATE_KEY: ${{ secrets.CI_PINS_APP_PRIVATE_KEY }}diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 97feaa9b1..39dff6f6f 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.9+ rev: v0.16.10hooks:- id: ruff-checkargs: [ --fix ]@@ -31,7 +31,7 @@ repos:hooks:- id: sphinx-scrapy- repo: https://github.com/zizmorcore/zizmor-pre-commit- rev: v1.28.0+ rev: v1.30.1hooks:- id: zizmorargs: [--no-progress, --fix]diff --git a/docs/intro/install.rst b/docs/intro/install.rstindex 77eb7a4cc..681076510 100644--- a/docs/intro/install.rst+++ b/docs/intro/install.rst@@ -9,7 +9,7 @@ Installation guideSupported Python versions=========================-Scrapy requires Python 3.10+, either the CPython implementation (default) or+Scrapy requires Python 3.11+, either the CPython implementation (default) orthe PyPy implementation (see :ref:`python:implementations`)... _intro-install-scrapy:diff --git a/pyproject.toml b/pyproject.tomlindex dca1f2513..a93fae1c3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -275,7 +275,7 @@ disable = [# requires `pylint_per_file_ignores` pluginper-file-ignores = [# Extended list of ones that we may want to address, only for tests- "./tests/*:abstract-method,arguments-renamed,dangerous-default-value,pointless-statement,raise-missing-from,unidiomatic-typecheck,unnecessary-dunder-call,used-before-assignment",+ "tests/*:abstract-method,arguments-renamed,dangerous-default-value,pointless-statement,raise-missing-from,unidiomatic-typecheck,unnecessary-dunder-call,used-before-assignment",][tool.pytest.ini_options]diff --git a/scrapy/commands/__init__.py b/scrapy/commands/__init__.pyindex 9dc2d3f7d..c87c390c1 100644--- a/scrapy/commands/__init__.py+++ b/scrapy/commands/__init__.py@@ -179,7 +179,7 @@ class ScrapyCommand(ABC):raise NotImplementedError-class BaseRunSpiderCommand(ScrapyCommand):+class BaseRunSpiderCommand(ScrapyCommand, ABC):"""Common class used to share functionality between the crawl, parse and runspider commands"""diff --git a/scrapy/commands/edit.py b/scrapy/commands/edit.pyindex fa75cb09c..243c17c24 100644--- a/scrapy/commands/edit.py+++ b/scrapy/commands/edit.py@@ -51,7 +51,7 @@ class Command(ScrapyCommand):raise UsageErrorassert self.settings is not None- editor = self.settings["EDITOR"]+ editor = self.settings["EDITOR"] # pylint: disable=unsubscriptable-objectspider_loader = get_spider_loader(self.settings)try:spidercls = spider_loader.load(args[0])diff --git a/scrapy/commands/genspider.py b/scrapy/commands/genspider.pyindex 79c25cd98..2790310ba 100644--- a/scrapy/commands/genspider.py+++ b/scrapy/commands/genspider.py@@ -120,7 +120,7 @@ class Command(ScrapyCommand):module, name, url, opts.template, template_file)if opts.edit:- self.exitcode = _edit_file(self.settings["EDITOR"], spider_file)+ self.exitcode = _edit_file(self.settings["EDITOR"], spider_file) # pylint: disable=unsubscriptable-objectdef _generate_template_variables(self,@@ -153,7 +153,7 @@ class Command(ScrapyCommand):assert self.settings is not Nonetvars = self._generate_template_variables(module, name, url, template_name)if self.settings.get("NEWSPIDER_MODULE"):- spiders_module = import_module(self.settings["NEWSPIDER_MODULE"])+ spiders_module = import_module(self.settings["NEWSPIDER_MODULE"]) # pylint: disable=unsubscriptable-objectassert spiders_module.__file__spiders_dir = Path(spiders_module.__file__).parent.resolve()else:@@ -215,7 +215,7 @@ class Command(ScrapyCommand):return True# a file with the same name exists in the target directory- spiders_module = import_module(self.settings["NEWSPIDER_MODULE"])+ spiders_module = import_module(self.settings["NEWSPIDER_MODULE"]) # pylint: disable=unsubscriptable-objectspiders_dir = Path(cast("str", spiders_module.__file__)).parentspiders_dir_abs = spiders_dir.resolve()path = spiders_dir_abs / (name + ".py")@@ -230,7 +230,7 @@ class Command(ScrapyCommand):assert self.settings is not Nonereturn str(Path(- self.settings["TEMPLATES_DIR"] or Path(scrapy.__path__[0], "templates"),+ self.settings["TEMPLATES_DIR"] or Path(scrapy.__path__[0], "templates"), # pylint: disable=unsubscriptable-object"spiders",))diff --git a/scrapy/commands/startproject.py b/scrapy/commands/startproject.pyindex 497c24e9e..5b42d65eb 100644--- a/scrapy/commands/startproject.py+++ b/scrapy/commands/startproject.py@@ -135,7 +135,7 @@ class Command(ScrapyCommand):assert self.settings is not Nonereturn str(Path(- self.settings["TEMPLATES_DIR"] or Path(scrapy.__path__[0], "templates"),+ self.settings["TEMPLATES_DIR"] or Path(scrapy.__path__[0], "templates"), # pylint: disable=unsubscriptable-object"project",))diff --git a/scrapy/core/downloader/middleware.py b/scrapy/core/downloader/middleware.pyindex 3b9f4e11e..14e11516e 100644--- a/scrapy/core/downloader/middleware.py+++ b/scrapy/core/downloader/middleware.py@@ -33,7 +33,7 @@ if TYPE_CHECKING:from scrapy.settings import BaseSettings-class DownloaderMiddlewareManager(MiddlewareManager):+class DownloaderMiddlewareManager(MiddlewareManager): # pylint: disable=abstract-methodcomponent_name = "downloader middleware"def __init__(self, *middlewares: Any, crawler: Crawler | None = None) -> None:diff --git a/scrapy/core/spidermw.py b/scrapy/core/spidermw.pyindex d910ec598..6d394314b 100644--- a/scrapy/core/spidermw.py+++ b/scrapy/core/spidermw.py@@ -46,7 +46,7 @@ ScrapeFunc: TypeAlias = Callable[]-class SpiderMiddlewareManager(MiddlewareManager):+class SpiderMiddlewareManager(MiddlewareManager): # pylint: disable=abstract-methodcomponent_name = "spider middleware"@classmethoddiff --git a/scrapy/downloadermiddlewares/retry.py b/scrapy/downloadermiddlewares/retry.pyindex 28126a4d4..5abfe23de 100644--- a/scrapy/downloadermiddlewares/retry.py+++ b/scrapy/downloadermiddlewares/retry.py@@ -9,7 +9,7 @@ RETRY_HTTP_CODES - which HTTP response codes to retryfrom __future__ import annotations-from logging import Logger, getLevelName, getLogger+from logging import Logger, getLevelNamesMapping, getLoggerfrom typing import TYPE_CHECKING, Selffrom scrapy.exceptions import NotConfigured@@ -121,8 +121,8 @@ def get_retry_request(if give_up_log_level is None:give_up_log_level = settings["RETRY_GIVE_UP_LOG_LEVEL"]if isinstance(give_up_log_level, str):- level = getLevelName(give_up_log_level)- if not isinstance(level, int):+ level = getLevelNamesMapping().get(give_up_log_level)+ if level is None:raise ValueError(f"Invalid give-up log level: {give_up_log_level!r}")give_up_log_level = levelstats.inc_value(f"{stats_base_key}/max_reached")diff --git a/scrapy/extension.py b/scrapy/extension.pyindex 05cce326b..61c90c2bd 100644--- a/scrapy/extension.py+++ b/scrapy/extension.py@@ -15,7 +15,7 @@ if TYPE_CHECKING:from scrapy.settings import Settings-class ExtensionManager(MiddlewareManager):+class ExtensionManager(MiddlewareManager): # pylint: disable=abstract-methodcomponent_name = "extension"@classmethoddiff --git a/scrapy/extensions/remote_control.py b/scrapy/extensions/remote_control.pyindex d8d648790..417edc1bf 100644--- a/scrapy/extensions/remote_control.py+++ b/scrapy/extensions/remote_control.py@@ -279,9 +279,9 @@ class RemoteControl:eval_result = eval(code_obj, ns) # noqa: S307 - arbitrary code by designif inspect.iscoroutine(eval_result):try:- await asyncio.wait_for(eval_result, timeout)+ async with asyncio.timeout(timeout):+ await eval_resultexcept TimeoutError:- # wait_for cancelled the coroutine at an await point.status = "timeout"except Exception:# intentionally doesn't catch asyncio.CancelledError, which is a BaseExceptiondiff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.pyindex 7bf230ae0..ae68918c4 100644--- a/scrapy/pipelines/files.py+++ b/scrapy/pipelines/files.py@@ -20,7 +20,6 @@ from ftplib import FTPfrom io import BytesIOfrom pathlib import Pathfrom typing import (- IO,TYPE_CHECKING,Any,ClassVar,@@ -72,23 +71,6 @@ def _to_string(path: str | PathLike[str]) -> str:return str(path) # convert a Path object to string-def _md5sum(file: IO[bytes]) -> str:- """Calculate the md5 checksum of a file-like object without reading its- whole content in memory.-- >>> from io import BytesIO- >>> _md5sum(BytesIO(b'file content to hash'))- '784406af91dd5a54fbb9c84c2236595a'- """- m = hashlib.md5() # noqa: S324- while True:- d = file.read(8096)- if not d:- break- m.update(d)- return m.hexdigest()--class StatInfo(TypedDict, total=False):checksum: strlast_modified: float@@ -117,10 +99,10 @@ class FSFilesStore:if "://" in basedir:basedir = basedir.split("://", 1)[1]self.basedir: str = basedir- self._mkdir(Path(self.basedir))self.created_directories: defaultdict[MediaPipeline.SpiderInfo, set[str]] = (defaultdict(set))+ self._mkdir(Path(self.basedir))def persist_file(self,@@ -144,7 +126,7 @@ class FSFilesStore:return {}with absolute_path.open("rb") as f:- checksum = _md5sum(f)+ checksum = hashlib.file_digest(f, "md5").hexdigest()return {"last_modified": last_modified, "checksum": checksum}@@ -594,7 +576,7 @@ class FilesPipeline(MediaPipeline):age_seconds = time.time() - last_modifiedage_days = age_seconds / 60 / 60 / 24- if self.expires >= 0 and age_days > self.expires:+ if 0 <= self.expires < age_days:return None # returning None force downloadreferer = referer_str(request)@@ -734,7 +716,7 @@ class FilesPipeline(MediaPipeline):) -> str:path = self.file_path(request, response=response, info=info, item=item)buf = BytesIO(response.body)- checksum = _md5sum(buf)+ checksum = hashlib.file_digest(buf, "md5").hexdigest()buf.seek(0)await ensure_awaitable(self.store.persist_file(path, buf, info))return checksumdiff --git a/scrapy/pipelines/images.py b/scrapy/pipelines/images.pyindex 370ef1a9f..51e10c671 100644--- a/scrapy/pipelines/images.py+++ b/scrapy/pipelines/images.py@@ -18,7 +18,7 @@ from itemadapter import ItemAdapterfrom scrapy.exceptions import NotConfigured, ScrapyDeprecationWarningfrom scrapy.http import Request, Responsefrom scrapy.http.request import NO_CALLBACK-from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStore, _md5sum+from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStorefrom scrapy.pipelines.media import FileExceptionfrom scrapy.utils.defer import ensure_awaitablefrom scrapy.utils.python import to_bytes@@ -155,7 +155,7 @@ class ImagesPipeline(FilesPipeline):for path, image, buf in self.get_images(response, request, info, item=item):if checksum is None:buf.seek(0)- checksum = _md5sum(buf)+ checksum = hashlib.file_digest(buf, "md5").hexdigest()width, height = image.sizecontent_type = self._Image.MIME.get(image.format or "JPEG", "image/jpeg")await ensure_awaitable(diff --git a/scrapy/utils/asyncio.py b/scrapy/utils/asyncio.pyindex a7f372482..ba232459a 100644--- a/scrapy/utils/asyncio.py+++ b/scrapy/utils/asyncio.py@@ -15,7 +15,6 @@ from typing import (Self,TypeVar,TypeVarTuple,- Unpack,)from twisted.internet.defer import Deferred@@ -242,7 +241,7 @@ def create_looping_call(def call_later(- delay: float, func: Callable[[Unpack[_Ts]], object], *args: *_Ts+ delay: float, func: Callable[[*_Ts], object], *args: *_Ts) -> CallLaterResult:"""Schedule a function to be called after a delay.diff --git a/scrapy/utils/log.py b/scrapy/utils/log.pyindex f94abfa07..ab9b696d8 100644--- a/scrapy/utils/log.py+++ b/scrapy/utils/log.py@@ -327,8 +327,7 @@ def logformatter_adapter(return (level, message, args)-# LoggerAdapter is only parameterized since Python 3.11-class SpiderLoggerAdapter(logging.LoggerAdapter): # type: ignore[type-arg]+class SpiderLoggerAdapter(logging.LoggerAdapter[logging.Logger]):def process(self, msg: str, kwargs: MutableMapping[str, Any]) -> tuple[str, MutableMapping[str, Any]]:diff --git a/tests/test_http_response_text.py b/tests/test_http_response_text.pyindex d3bf4d7c0..31634d3d5 100644--- a/tests/test_http_response_text.py+++ b/tests/test_http_response_text.py@@ -273,7 +273,8 @@ class TestTextResponse(TestResponseBase):assert isinstance(response.selector, Selector)assert response.selector.type == "html"- assert response.selector is response.selector # property is cached+ # property is cached+ assert response.selector is response.selector # pylint: disable=comparison-with-itselfassert response.selector.response is responseassert response.selector.xpath("//title/text()").getall() == ["Some page"]@@ -628,7 +629,8 @@ class TestXmlResponse(TestTextResponse):assert isinstance(response.selector, Selector)assert response.selector.type == "xml"- assert response.selector is response.selector # property is cached+ # property is cached+ assert response.selector is response.selector # pylint: disable=comparison-with-itselfassert response.selector.response is responseassert response.selector.xpath("//elem/text()").getall() == ["value"]diff --git a/tests/test_pipeline_images.py b/tests/test_pipeline_images.pyindex 60f79926f..c8b0fffa3 100644--- a/tests/test_pipeline_images.py+++ b/tests/test_pipeline_images.py@@ -1,6 +1,7 @@from __future__ import annotationsimport dataclasses+import hashlibimport ioimport randomimport sys@@ -17,7 +18,7 @@ from itemadapter import ItemAdapterfrom scrapy.exceptions import NotConfiguredfrom scrapy.http import Request, Responsefrom scrapy.item import Field, Item-from scrapy.pipelines.files import GCSFilesStore, S3FilesStore, _md5sum+from scrapy.pipelines.files import GCSFilesStore, S3FilesStorefrom scrapy.pipelines.images import ImageException, ImagesPipelinefrom scrapy.utils.misc import build_from_crawlerfrom scrapy.utils.test import get_crawler@@ -250,7 +251,7 @@ class TestImagesPipeline:)buf.seek(0)- assert checksum == _md5sum(buf)+ assert checksum == hashlib.file_digest(buf, "md5").hexdigest()name = "3fd165099d8e71b8a48b2683946e64dbfad8b52d.jpg"assert Path(self.tempdir, "full", name).read_bytes() == buf.getvalue()assert Path(self.tempdir, "thumbs", "small", name).exists()diff --git a/tests/test_spider_sitemap.py b/tests/test_spider_sitemap.pyindex 879e987b3..d5ab57deb 100644--- a/tests/test_spider_sitemap.py+++ b/tests/test_spider_sitemap.py@@ -514,4 +514,4 @@ Sitemap: /sitemap-relative-url.xmlrequest = requests[0]assert request.url == "https://toscrape.com/sitemap.xml"assert request.dont_filter is False- assert request.callback == spider._parse_sitemap+ assert request.callback == spider._parse_sitemap # pylint: disable=comparison-with-callablediff --git a/tests/test_utils_project.py b/tests/test_utils_project.pyindex be64c8b36..3cc56b283 100644--- a/tests/test_utils_project.py+++ b/tests/test_utils_project.py@@ -101,7 +101,7 @@ def test_project_data_dir_default(proj_path: Path) -> None:def test_project_data_dir_from_scrapy_cfg(proj_path: Path) -> None:datadir = proj_path / "custom-datadir"- Path("scrapy.cfg").write_text(f"[datadir]\ndefault = {datadir}\n")+ Path("scrapy.cfg").write_text(f"[datadir]\ndefault = {datadir}\n", encoding="utf-8")assert Path(project_data_dir()) == datadirassert datadir.is_dir()diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex 9135b1171..dd3aff629 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -1003,7 +1003,7 @@ class TestHttpBase(ABC):assert response.body == path.encode()-class TestHttpsBase(TestHttpBase):+class TestHttpsBase(TestHttpBase, ABC):is_secure = Truetls_log_message = (@@ -1151,7 +1151,7 @@ class TestSimpleHttpsBase(ABC):assert response.body == b"0123456789"-class TestHttpsWrongHostnameBase(TestSimpleHttpsBase):+class TestHttpsWrongHostnameBase(TestSimpleHttpsBase, ABC):# above tests use a server certificate for "localhost",# client connection to "localhost" too.# here we test that even if the server certificate is for another domain,@@ -1161,24 +1161,24 @@ class TestHttpsWrongHostnameBase(TestSimpleHttpsBase):certfile = "keys/example-com.cert.pem"-class TestHttpsInvalidDNSIdBase(TestSimpleHttpsBase):+class TestHttpsInvalidDNSIdBase(TestSimpleHttpsBase, ABC):"""Connect to HTTPS hosts with IP while certificate uses domain names IDs."""host = "127.0.0.1"-class TestHttpsInvalidDNSPatternBase(TestSimpleHttpsBase):+class TestHttpsInvalidDNSPatternBase(TestSimpleHttpsBase, ABC):"""Connect to HTTPS hosts where the certificate are issued to an ip instead of a domain."""keyfile = "keys/localhost.ip.key"certfile = "keys/localhost.ip.crt"-class TestHttpsCustomCiphersBase(TestSimpleHttpsBase):+class TestHttpsCustomCiphersBase(TestSimpleHttpsBase, ABC):cipher_string = "CAMELLIA256-SHA"-class TestHttpsDefaultCiphersBase(TestSimpleHttpsBase):+class TestHttpsDefaultCiphersBase(TestSimpleHttpsBase, ABC):"""A ``None`` cipher list leaves the TLS library defaults in place."""client_settings: dict[str, Any] | None = {"DOWNLOADER_CLIENT_TLS_CIPHERS": None}diff --git a/tests/utils/bases/http_request.py b/tests/utils/bases/http_request.pyindex b6029e587..da13fe94c 100644--- a/tests/utils/bases/http_request.py+++ b/tests/utils/bases/http_request.py@@ -380,7 +380,7 @@ class TestRequestBase(ABC):assert request._flags is Noneassert request.flags == []- assert request.flags is request.flags+ assert request.flags is request.flags # pylint: disable=comparison-with-itselfassert request._flags == []original_flags = request.flagsrequest.flags = None@@ -390,7 +390,7 @@ class TestRequestBase(ABC):assert request._cookies is Noneassert request.cookies == {}- assert request.cookies is request.cookies+ assert request.cookies is request.cookies # pylint: disable=comparison-with-itselfassert request._cookies == {}original_cookies = request.cookiesrequest.cookies = None@@ -405,7 +405,7 @@ class TestRequestBase(ABC):else:assert request._headers is Noneassert request.headers == {}- assert request.headers is request.headers+ assert request.headers is request.headers # pylint: disable=comparison-with-itselfassert isinstance(request.headers, Headers)assert isinstance(request._headers, Headers)original_headers = request.headersdiff --git a/tests/utils/bases/http_response.py b/tests/utils/bases/http_response.pyindex d23c3ebe1..95cdadea8 100644--- a/tests/utils/bases/http_response.py+++ b/tests/utils/bases/http_response.py@@ -187,7 +187,7 @@ class TestResponseBase(ABC):assert response._flags is Noneassert response.flags == []- assert response.flags is response.flags+ assert response.flags is response.flags # pylint: disable=comparison-with-itselfassert response._flags == []original_flags = response.flagsresponse.flags = None@@ -197,7 +197,7 @@ class TestResponseBase(ABC):assert response._headers is Noneassert response.headers == {}- assert response.headers is response.headers+ assert response.headers is response.headers # pylint: disable=comparison-with-itselfassert isinstance(response.headers, Headers)assert isinstance(response._headers, Headers)original_headers = response.headersdiff --git a/tox.ini b/tox.iniindex 2969d14d2..fb16942a3 100644--- a/tox.ini+++ b/tox.ini@@ -69,24 +69,23 @@ commands =[testenv:mypy]basepython = python3.11deps =- mypy==2.3.1+ mypy==2.4.0typing-extensions==4.16.0Pillow==12.3.0- Protego==0.6.2+ Protego==0.7.0Twisted==26.4.0aiohttp==3.14.3attrs==26.1.0backports.zstd==1.7.0- boto3-stubs[s3]==1.43.98+ boto3-stubs[s3]==1.43.107botocore-stubs==1.43.67colorlog==6.12.0h2==4.4.1- httpx2==2.13.0+ httpx2==2.13.1itemadapter==0.13.1- platformdirs==4.11.11+ platformdirs==4.12.2ptpython==3.0.32- # newer ones require newer Python- ipython==8.39.0+ ipython==9.17.1pyOpenSSL==26.4.0pytest==9.1.1socksio==1.0.0@@ -94,8 +93,8 @@ deps =types-defusedxml==0.7.0.20260504types-lxml==2026.2.16types-pexpect==4.9.0.20260518- uvloop==0.22.1- w3lib==2.4.1+ uvloop==0.23.0+ w3lib==2.5.0commands =mypy {posargs:scrapy tests}@@ -120,8 +119,8 @@ commands =basepython = python3.14deps ={[testenv:extra-deps]deps}- pylint==4.0.6- pylint-per-file-ignores # https://github.com/pylint-dev/pylint/issues/3767#issuecomment-1319916278+ pylint==4.1.1+ pylint-per-file-ignores==4.0.0commands =pylint {posargs:conftest.py docs extras scrapy tests}@@ -129,7 +128,7 @@ commands =basepython = python3deps =twine==7.0.0- build==1.5.0+ build==1.6.1commands =python -m build --sdisttwine check dist/*