Skip to content

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.yml
index 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.yml
secrets:
CI_PINS_APP_PRIVATE_KEY: ${{ secrets.CI_PINS_APP_PRIVATE_KEY }}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 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.10
hooks:
- id: ruff-check
args: [ --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.1
hooks:
- id: zizmor
args: [--no-progress, --fix]
diff --git a/docs/intro/install.rst b/docs/intro/install.rst
index 77eb7a4cc..681076510 100644
--- a/docs/intro/install.rst
+++ b/docs/intro/install.rst
@@ -9,7 +9,7 @@ Installation guide
Supported Python versions
=========================
-Scrapy requires Python 3.10+, either the CPython implementation (default) or
+Scrapy requires Python 3.11+, either the CPython implementation (default) or
the PyPy implementation (see :ref:`python:implementations`).
.. _intro-install-scrapy:
diff --git a/pyproject.toml b/pyproject.toml
index dca1f2513..a93fae1c3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -275,7 +275,7 @@ disable = [
# requires `pylint_per_file_ignores` plugin
per-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__.py
index 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.py
index fa75cb09c..243c17c24 100644
--- a/scrapy/commands/edit.py
+++ b/scrapy/commands/edit.py
@@ -51,7 +51,7 @@ class Command(ScrapyCommand):
raise UsageError
assert self.settings is not None
- editor = self.settings["EDITOR"]
+ editor = self.settings["EDITOR"] # pylint: disable=unsubscriptable-object
spider_loader = get_spider_loader(self.settings)
try:
spidercls = spider_loader.load(args[0])
diff --git a/scrapy/commands/genspider.py b/scrapy/commands/genspider.py
index 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-object
def _generate_template_variables(
self,
@@ -153,7 +153,7 @@ class Command(ScrapyCommand):
assert self.settings is not None
tvars = 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-object
assert 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-object
spiders_dir = Path(cast("str", spiders_module.__file__)).parent
spiders_dir_abs = spiders_dir.resolve()
path = spiders_dir_abs / (name + ".py")
@@ -230,7 +230,7 @@ class Command(ScrapyCommand):
assert self.settings is not None
return 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.py
index 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 None
return 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.py
index 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-method
component_name = "downloader middleware"
def __init__(self, *middlewares: Any, crawler: Crawler | None = None) -> None:
diff --git a/scrapy/core/spidermw.py b/scrapy/core/spidermw.py
index 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-method
component_name = "spider middleware"
@classmethod
diff --git a/scrapy/downloadermiddlewares/retry.py b/scrapy/downloadermiddlewares/retry.py
index 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 retry
from __future__ import annotations
-from logging import Logger, getLevelName, getLogger
+from logging import Logger, getLevelNamesMapping, getLogger
from typing import TYPE_CHECKING, Self
from 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 = level
stats.inc_value(f"{stats_base_key}/max_reached")
diff --git a/scrapy/extension.py b/scrapy/extension.py
index 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-method
component_name = "extension"
@classmethod
diff --git a/scrapy/extensions/remote_control.py b/scrapy/extensions/remote_control.py
index 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 design
if inspect.iscoroutine(eval_result):
try:
- await asyncio.wait_for(eval_result, timeout)
+ async with asyncio.timeout(timeout):
+ await eval_result
except TimeoutError:
- # wait_for cancelled the coroutine at an await point.
status = "timeout"
except Exception:
# intentionally doesn't catch asyncio.CancelledError, which is a BaseException
diff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.py
index 7bf230ae0..ae68918c4 100644
--- a/scrapy/pipelines/files.py
+++ b/scrapy/pipelines/files.py
@@ -20,7 +20,6 @@ from ftplib import FTP
from io import BytesIO
from pathlib import Path
from 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: str
last_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_modified
age_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 download
referer = 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 checksum
diff --git a/scrapy/pipelines/images.py b/scrapy/pipelines/images.py
index 370ef1a9f..51e10c671 100644
--- a/scrapy/pipelines/images.py
+++ b/scrapy/pipelines/images.py
@@ -18,7 +18,7 @@ from itemadapter import ItemAdapter
from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning
from scrapy.http import Request, Response
from scrapy.http.request import NO_CALLBACK
-from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStore, _md5sum
+from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStore
from scrapy.pipelines.media import FileException
from scrapy.utils.defer import ensure_awaitable
from 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.size
content_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.py
index 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.py
index 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.py
index 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-itself
assert response.selector.response is response
assert 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-itself
assert response.selector.response is response
assert response.selector.xpath("//elem/text()").getall() == ["value"]
diff --git a/tests/test_pipeline_images.py b/tests/test_pipeline_images.py
index 60f79926f..c8b0fffa3 100644
--- a/tests/test_pipeline_images.py
+++ b/tests/test_pipeline_images.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import dataclasses
+import hashlib
import io
import random
import sys
@@ -17,7 +18,7 @@ from itemadapter import ItemAdapter
from scrapy.exceptions import NotConfigured
from scrapy.http import Request, Response
from scrapy.item import Field, Item
-from scrapy.pipelines.files import GCSFilesStore, S3FilesStore, _md5sum
+from scrapy.pipelines.files import GCSFilesStore, S3FilesStore
from scrapy.pipelines.images import ImageException, ImagesPipeline
from scrapy.utils.misc import build_from_crawler
from 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.py
index 879e987b3..d5ab57deb 100644
--- a/tests/test_spider_sitemap.py
+++ b/tests/test_spider_sitemap.py
@@ -514,4 +514,4 @@ Sitemap: /sitemap-relative-url.xml
request = 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-callable
diff --git a/tests/test_utils_project.py b/tests/test_utils_project.py
index 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()) == datadir
assert datadir.is_dir()
diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.py
index 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 = True
tls_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.py
index 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 None
assert request.flags == []
- assert request.flags is request.flags
+ assert request.flags is request.flags # pylint: disable=comparison-with-itself
assert request._flags == []
original_flags = request.flags
request.flags = None
@@ -390,7 +390,7 @@ class TestRequestBase(ABC):
assert request._cookies is None
assert request.cookies == {}
- assert request.cookies is request.cookies
+ assert request.cookies is request.cookies # pylint: disable=comparison-with-itself
assert request._cookies == {}
original_cookies = request.cookies
request.cookies = None
@@ -405,7 +405,7 @@ class TestRequestBase(ABC):
else:
assert request._headers is None
assert request.headers == {}
- assert request.headers is request.headers
+ assert request.headers is request.headers # pylint: disable=comparison-with-itself
assert isinstance(request.headers, Headers)
assert isinstance(request._headers, Headers)
original_headers = request.headers
diff --git a/tests/utils/bases/http_response.py b/tests/utils/bases/http_response.py
index 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 None
assert response.flags == []
- assert response.flags is response.flags
+ assert response.flags is response.flags # pylint: disable=comparison-with-itself
assert response._flags == []
original_flags = response.flags
response.flags = None
@@ -197,7 +197,7 @@ class TestResponseBase(ABC):
assert response._headers is None
assert response.headers == {}
- assert response.headers is response.headers
+ assert response.headers is response.headers # pylint: disable=comparison-with-itself
assert isinstance(response.headers, Headers)
assert isinstance(response._headers, Headers)
original_headers = response.headers
diff --git a/tox.ini b/tox.ini
index 2969d14d2..fb16942a3 100644
--- a/tox.ini
+++ b/tox.ini
@@ -69,24 +69,23 @@ commands =
[testenv:mypy]
basepython = python3.11
deps =
- mypy==2.3.1
+ mypy==2.4.0
typing-extensions==4.16.0
Pillow==12.3.0
- Protego==0.6.2
+ Protego==0.7.0
Twisted==26.4.0
aiohttp==3.14.3
attrs==26.1.0
backports.zstd==1.7.0
- boto3-stubs[s3]==1.43.98
+ boto3-stubs[s3]==1.43.107
botocore-stubs==1.43.67
colorlog==6.12.0
h2==4.4.1
- httpx2==2.13.0
+ httpx2==2.13.1
itemadapter==0.13.1
- platformdirs==4.11.11
+ platformdirs==4.12.2
ptpython==3.0.32
- # newer ones require newer Python
- ipython==8.39.0
+ ipython==9.17.1
pyOpenSSL==26.4.0
pytest==9.1.1
socksio==1.0.0
@@ -94,8 +93,8 @@ deps =
types-defusedxml==0.7.0.20260504
types-lxml==2026.2.16
types-pexpect==4.9.0.20260518
- uvloop==0.22.1
- w3lib==2.4.1
+ uvloop==0.23.0
+ w3lib==2.5.0
commands =
mypy {posargs:scrapy tests}
@@ -120,8 +119,8 @@ commands =
basepython = python3.14
deps =
{[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.0
commands =
pylint {posargs:conftest.py docs extras scrapy tests}
@@ -129,7 +128,7 @@ commands =
basepython = python3
deps =
twine==7.0.0
- build==1.5.0
+ build==1.6.1
commands =
python -m build --sdist
twine check dist/*