使用 mypy 检查 Spider 回调的类型提示覆盖率。

解读

在国内一线互联网公司的 Scrapy 面试中,类型安全与工程可维护性是高级爬虫岗的硬性指标。面试官抛出此题,意在考察候选人能否把“动态语言”写成“可静态检查”的工业级代码。核心痛点是:

  1. Scrapy 的回调靠字符串名字解耦,Request.cb_kwargs 与 response.follow 极易丢失类型;
  2. 默认生成的 Spider 模板不带任何类型标注,mypy 100% 报 Any;
  3. 国内很多团队直接 scrapy genspider 后开抓,CI 阶段未接入 mypy,导致线上因字段拼写错误踩坑。
    候选人必须给出一条“不改 Scrapy 源码、不破坏兼容、可增量落地”的完整方案,并能把覆盖率量化到 90% 以上。

知识点

  1. PEP 561 兼容:Scrapy 2.11 起自带 py.typed,mypy 能识别其公共 API。
  2. 泛型 Response:scrapy.http.Response 是泛型类 Response[TextResponse],可继承后加类型实参。
  3. 回调协议:使用 typing.Protocol 定义 ParseCallback = Callable[[Response[Any], KwArg(Any)], Iterable[Any]],解决字符串回调无类型问题。
  4. Item 类型:scrapy.Item 是 dict-like,必须显式继承 TypedDict 或 dataclass,否则 mypy 视为 Any。
  5. 覆盖率统计:mypy --cobertura-xml-report cov.xml 结合 diff-cover 可在 MR 阶段卡点,国内 GitLab-CI 常用此方案。
  6. 增量治理:通过 mypy --allow-untyped-globals --follow-imports=skip 先让旧代码 pass,再用 # type: ignore[code] 逐步消除技术债。

答案

  1. 项目级配置
    在 pyproject.toml 中锁定:

    [tool.mypy]
    python_version = "3.11"
    strict = true
    disallow_any_generics = true
    plugins = ["pydantic.mypy"]   # 若用 Item 的 dataclass 版本
    
  2. 强类型 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。
  3. 覆盖率卡点
    在 .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 直接失败,符合国内“质量门禁”要求。

  4. 遗留代码兼容
    对老 Spider 先加 __init__.py 级 mypy: ignore-errors,再用 scripts/typed_migrate.py 批量插入 # TODO(type) 标记,两周一轮迭代即可把覆盖率从 30% 拉到 90%。

拓展思考

  1. 异步回调类型
    如果项目用到 scrapy-twisted 的 async def parse,需把返回类型改为 AsyncIterable[MyItem],并启用 mypy --asyncio-mode=strict,否则生成器与协程混用会漏检。

  2. 分布式场景
    使用 scrapy-redis 时,推送的 Request 经过 redis 序列化后会丢失泛型,可在 Request.meta 里塞 _mypy_type_hint 字段,落地端反序列化后手动 cast,保证多机节点类型一致。

  3. 与 pydantic 结合
    国内很多团队把 Item 换成 pydantic.BaseModel,利用 mypy 插件可把字段校验错误提前到静态阶段,但注意 BaseModel 不是 dict,需在 Pipeline 里 .dict() 后再入库,避免 ORM 报错。

  4. 性能权衡
    过度泛型会让 mypy 检查时间翻倍,建议把 strict_optional = false 打开,并对热路径的回调加 decorator_cache,在 10 万行代码规模下保持 CI 检查 < 30 s,符合国内“分钟级流水线”诉求。