在 Pipeline 中集成 Great Expectations 实现字段级断言。

解读

国内中大型爬虫项目普遍要求“数据质量可验证、问题可追溯、异常可熔断”。Great Expectations(GE)是字段级数据质量校验的事实标准,支持 300+ 内置 Expectation,可输出中文报告并对接飞书/企业微信。面试官想确认三点:

  1. 你是否理解 Scrapy Pipeline 的异步、批处理特性;
  2. 能否把 GE 的批式校验无缝嵌入,而不阻塞 Twisted 事件循环;
  3. 是否具备“失败即熔断、报告即证据”的工程化思维,满足国内合规审计需求。

知识点

  1. Scrapy Pipeline 生命周期:open_spider → process_item → close_spider,全部运行在 Twisted 线程池,需避免同步 IO。
  2. Great Expectations 0.18+ 上下文管理:DataContext → Checkpoint → Validator → ExpectationSuite,支持内存 DataFrame 校验,无需落地中间文件。
  3. 异步转同步最佳实践:使用 crochet.wait_for 或 asyncio.run_coroutine_threadsafe,把 GE 的 validator.validate() 封装成 Twisted 可调用的回调,超时即熔断。
  4. 字段级断言示例:expect_column_values_to_be_between、expect_column_values_to_match_regex,支持中文列名与自定义 meta 信息。
  5. 国内监管要点:校验失败需留存**“数据质量报告 + 原始 item 快照”**双证据,报告格式为 HTML+JSON,存储在 MinIO 或 OSS,保存周期 ≥ 7 年。

答案

  1. 项目结构
    project/ ├── great_expectations/ │ ├── expectations/ │ │ └── items_suite.json │ └── checkpoints/ │ └── items_ck.py ├── scrapy_pipelines/ │ └── ge_pipeline.py └── settings.py

  2. 在 great_expectations/checkpoints/items_ck.py 中预定义 suite
    from great_expectations.checkpoint import SimpleCheckpoint from great_expectations.data_context import EphemeralDataContext

context = EphemeralDataContext() suite = context.create_expectation_suite("items_suite", overwrite_existing=True) suite.add_expectation( { "expectation_type": "expect_column_values_to_be_between", "kwargs": {"column": "price", "min_value": 0, "max_value": 100000}, "meta": {"业务描述": "国内电商价格不得为负,不得超 10 万"} } ) suite.add_expectation( { "expectation_type": "expect_column_values_to_match_regex", "kwargs": {"column": "mobile", "regex": r"^1[3-9]\d{9}$"}, "meta": {"业务描述": "手机号必须符合工信部号段"} } ) context.save_expectation_suite(suite)

  1. 编写 Scrapy Pipeline
    from twisted.internet import threads from great_expectations.data_context import EphemeralDataContext from great_expectations.validator import Validator import pandas as pd import great_expectations as ge from scrapy.exceptions import DropItem import json import datetime

class GEFieldValidationPipeline: def init(self): self.ctx = EphemeralDataContext() self.suite_name = "items_suite" self.batch_size = 1000 self.items_buffer = []

def open_spider(self, spider):
    spider.logger.info("【GE】字段级断言 Pipeline 启动")

def process_item(self, item, spider):
    self.items_buffer.append(dict(item))
    if len(self.items_buffer) >= self.batch_size:
        return self._validate_batch(spider)
    return item

def close_spider(self, spider):
    if self.items_buffer:
        self._validate_batch(spider)

def _validate_batch(self, spider):
    df = pd.DataFrame(self.items_buffer)
    self.items_buffer = []

    def _sync_validate():
        validator = self.ctx.get_validator(
            batch_request={
                "datasource_name": "pandas",
                "data_connector_name": "runtime",
                "data_asset_name": "scrapy_batch",
                "runtime_parameters": {"batch_data": df},
                "batch_identifiers": {"snapshot_id": datetime.datetime.now().isoformat()}
            },
            expectation_suite_name=self.suite_name
        )
        results = validator.validate()
        return results

    # 把同步校验丢到线程池,防止阻塞 Reactor
    results = threads.deferToThread(_sync_validate)

    def _on_success(validation_results):
        if not validation_results.success:
            # 国内审计要求:失败即熔断,留存证据
            ts = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            report_path = f"/data/qc_reports/scrapy_ge_{ts}.html"
            self.ctx.build_data_docs(site_names=["local_site"], resource_identifiers=[validation_results.run_id])
            spider.logger.error(f"【GE】字段断言失败,报告已生成:{report_path}")
            # 可选:把原始 item 快照写 OSS
            with open(f"/data/qc_snapshots/scrapy_items_{ts}.json", "w", encoding="utf-8") as f:
                json.dump(df.to_dict(orient="records"), f, ensure_ascii=False, indent=2)
            # 熔断:抛出 DropItem,终止后续 Pipeline
            raise DropItem("数据质量校验未通过,已熔断")

    def _on_failure(failure):
        spider.logger.error(f"【GE】校验线程异常:{failure.value}")
        raise DropItem("GE 校验线程异常")

    results.addCallback(_on_success).addErrback(_on_failure)
    return None  # 已消费,不再向下传递

4. settings.py 启用
ITEM_PIPELINES = { "scrapy_pipelines.ge_pipeline.GEFieldValidationPipeline": 300, }

  1. 运行效果
    爬虫在每满 1000 条或 spider 关闭时触发一次 GE 批校验;若字段不合规,立即熔断并生成中英文双语报告,满足国内数据治理规范。

拓展思考

  1. 分布式场景:结合 Scrapy-Redis,把校验失败批次写入 Redis Stream,由独立质检微服务消费,实现“抓取-校验”解耦,避免单点熔断拖慢全网采集。
  2. 实时流式校验:若业务对延迟敏感,可改用 Great Expectations Core “Expectation Validation Router” 模式,将单条 item 转为 Arrow RecordBatch,走内存校验,延迟 < 50 ms。
  3. 合规升级:国内金融、医药类项目需通过等保三级审计,可将 GE 报告自动上传至阿里云日志审计(SLS),并配置敏感字段脱敏规则(如身份证、银行卡),实现“校验-脱敏-留痕”一体化。