使用 mypy 检查 Spider 回调的类型提示覆盖率。
解读
在国内一线互联网公司的 Scrapy 面试中,类型安全与工程可维护性是高级爬虫岗的硬性指标。面试官抛出此题,意在考察候选人能否把“动态语言”写成“可静态检查”的工业级代码。核心痛点是:
- Scrapy 的回调靠字符串名字解耦,Request.cb_kwargs 与 response.follow 极易丢失类型;
- 默认生成的 Spider 模板不带任何类型标注,mypy 100% 报 Any;
- 国内很多团队直接
scrapy genspider后开抓,CI 阶段未接入 mypy,导致线上因字段拼写错误踩坑。
候选人必须给出一条“不改 Scrapy 源码、不破坏兼容、可增量落地”的完整方案,并能把覆盖率量化到 90% 以上。
知识点
- PEP 561 兼容:Scrapy 2.11 起自带
py.typed,mypy 能识别其公共 API。 - 泛型 Response:
scrapy.http.Response是泛型类Response[TextResponse],可继承后加类型实参。 - 回调协议:使用
typing.Protocol定义ParseCallback = Callable[[Response[Any], KwArg(Any)], Iterable[Any]],解决字符串回调无类型问题。 - Item 类型:
scrapy.Item是 dict-like,必须显式继承TypedDict或dataclass,否则 mypy 视为Any。 - 覆盖率统计:
mypy --cobertura-xml-report cov.xml结合diff-cover可在 MR 阶段卡点,国内 GitLab-CI 常用此方案。 - 增量治理:通过
mypy --allow-untyped-globals --follow-imports=skip先让旧代码 pass,再用# type: ignore[code]逐步消除技术债。
答案
-
项目级配置
在pyproject.toml中锁定:[tool.mypy] python_version = "3.11" strict = true disallow_any_generics = true plugins = ["pydantic.mypy"] # 若用 Item 的 dataclass 版本 -
强类型 Spider 模板
from __future__ import annotations import scrapy from typing import Iterable, Protocol from scrapy.http import Response class MyItem(scrapy.Item): title: str price: float class ParseCallback(Protocol): def __call__(self, response: Response, **kw: Any) -> Iterable[MyItem]: ... class TbSpider(scrapy.Spider): name = "tb" def start_requests(self) -> Iterable[scrapy.Request]: yield scrapy.Request("https://example.com", callback=self.parse_list) def parse_list(self, response: Response) -> Iterable[scrapy.Request]: for url in response.css("a::attr(href)").getall(): yield response.follow( url, callback=cast(ParseCallback, self.parse_detail), cb_kwargs={"category": "phone"} ) def parse_detail(self, response: Response, category: str) -> Iterable[MyItem]: yield MyItem( title=response.css("h1::text").get(), price=float(response.css(".price::text").re_first(r"\d+\.?\d*")), )关键点:
- 用 Protocol 显式声明回调签名,
cast一次即可让 mypy 跟踪后续调用。 - Item 字段全部标注类型,否则 mypy 报
Missing type parameters for generic Item。
- 用 Protocol 显式声明回调签名,
-
覆盖率卡点
在.gitlab-ci.yml中加:mypy: stage: test script: - pip install mypy diff-cover - mypy spiders/ --cobertura-xml-report coverage.xml - diff-cover coverage.xml --compare-branch=origin/master --fail-under=90若 MR 引入的新回调缺失类型,CI 直接失败,符合国内“质量门禁”要求。
-
遗留代码兼容
对老 Spider 先加__init__.py级mypy: ignore-errors,再用scripts/typed_migrate.py批量插入# TODO(type)标记,两周一轮迭代即可把覆盖率从 30% 拉到 90%。
拓展思考
-
异步回调类型
如果项目用到scrapy-twisted的async def parse,需把返回类型改为AsyncIterable[MyItem],并启用mypy --asyncio-mode=strict,否则生成器与协程混用会漏检。 -
分布式场景
使用scrapy-redis时,推送的 Request 经过 redis 序列化后会丢失泛型,可在Request.meta里塞_mypy_type_hint字段,落地端反序列化后手动cast,保证多机节点类型一致。 -
与 pydantic 结合
国内很多团队把 Item 换成pydantic.BaseModel,利用 mypy 插件可把字段校验错误提前到静态阶段,但注意BaseModel不是dict,需在 Pipeline 里.dict()后再入库,避免 ORM 报错。 -
性能权衡
过度泛型会让 mypy 检查时间翻倍,建议把strict_optional = false打开,并对热路径的回调加decorator_cache,在 10 万行代码规模下保持 CI 检查 < 30 s,符合国内“分钟级流水线”诉求。