如何构建可配置的数据清洗管道?插件化架构设计思路

解读

国内一线互联网公司的数据抓取量日均过亿条,清洗规则每周随业务策略调整。面试官想确认两点:

  1. 你能否把“写死在脚本里的 Beautiful Soup 逻辑”拆成可热插拔的配置;
  2. 当规则膨胀到上千条时,系统仍能保持 O(1) 级别的规则定位与 O(n) 级别的内存占用,且支持非研发人员在线变更。
    因此,回答必须围绕“配置驱动 + 插件注册 + 执行引擎”三层架构展开,并给出可落地的 Python 代码骨架,同时兼顾中文语义清洗、敏感词过滤、国标编码转换等国内特色需求。

知识点

  1. 配置模型:YAML/JSON 与 Pydantic 校验,支持“字段级”与“文档级”双粒度。
  2. 插件协议:使用 abc.ABC 定义统一入口 clean(bs: BeautifulSoup, context: Dict) -> BeautifulSoup,配合 entry_points 实现自动发现。
  3. 执行引擎:责任链 + 优先级队列,保证插件顺序可配置;采用生成器流式处理,单条内存占用 < 5 MB。
  4. 热加载:基于 watchdog 监听配置变更,通过 importlib.reload 重载插件模块,实现秒级生效。
  5. 国产兼容:内置 zhconv 繁简转换、gb18030 编码容错、敏感词 Trie 过滤,满足网信办合规要求。
  6. 降级与回滚:每条清洗规则输出带签名的中间副本,失败时自动回滚到上一版本,支持审计追溯。

答案

给出一个生产级最小可运行(MVP)框架,可直接嵌入 Scrapy 或独立调度。

  1. 目录结构
bs_cleaner/
├── cleaner/
│   ├── __init__.py
│   ├── api.py          # 对外接口
│   ├── engine.py       # 执行引擎
│   ├── plugin.py       # 插件基类
│   └── plugins/        # 插件目录
│       ├── __init__.py
│       ├── html5lib.py
│       ├── sensitive.py
│       └── normalize.py
├── config/
│   └── pipeline.yaml
└── tests/
  1. 插件协议(plugin.py)
from abc import ABC, abstractmethod
from bs4 import BeautifulSoup
from typing import Dict

class BasePlugin(ABC):
    priority: int = 100   # 数字越小越先执行
    name: str = ""

    @abstractmethod
    def clean(self, bs: BeautifulSoup, context: Dict) -> BeautifulSoup:
        raise NotImplementedError
  1. 配置示例(pipeline.yaml)
pipeline:
  - name: "html5lib"
    enabled: true
    priority: 10
    kwargs: {}
  - name: "normalize"
    enabled: true
    priority: 20
    kwargs:
      remove_blank: true
      lang: "zh-cn"
  - name: "sensitive"
    enabled: true
    priority: 30
    kwargs:
      word_path: "/data/sensitive_words.txt"
  1. 引擎实现(engine.py,核心 30 行)
import yaml, os, importlib, pkgutil
from typing import List
from bs4 import BeautifulSoup
from cleaner.plugin import BasePlugin

class PipelineEngine:
    def __init__(self, config_path: str):
        with open(config_path, encoding="utf-8") as f:
            self.cfg = yaml.safe_load(f)["pipeline"]
        self._plugins: List[BasePlugin] = []
        self._load_plugins()

    def _load_plugins(self):
        # 自动发现 cleaner.plugins 下的模块
        import cleaner.plugins as plug_pkg
        for _, name, _ in pkgutil.iter_modules(plug_pkg.__path__):
            importlib.import_module(f"cleaner.plugins.{name}")
        # 按配置顺序实例化
        registered = {cls.name: cls for cls in BasePlugin.__subclasses__()}
        for item in sorted(self.cfg, key=lambda x: x.get("priority", 100)):
            if not item["enabled"]:
                continue
            cls = registered[item["name"]]
            self._plugins.append(cls(**item.get("kwargs", {})))

    def clean(self, html: str) -> str:
        bs = BeautifulSoup(html, "lxml")
        context = {}
        for p in self._plugins:
            bs = p.clean(bs, context)
        return str(bs)
  1. 两个内置插件示例
# normalize.py
import zhconv, re
from cleaner.plugin import BasePlugin

class NormalizePlugin(BasePlugin):
    name = "normalize"
    priority = 20

    def __init__(self, remove_blank=True, lang="zh-cn"):
        self.remove_blank = remove_blank
        self.lang = lang

    def clean(self, bs, context):
        for tag in bs.find_all(text=True):
            text = tag.string or ""
            if self.lang == "zh-cn":
                text = zhconv.convert(text, "zh-cn")
            if self.remove_blank:
                text = re.sub(r"[\s\u200b]+", " ", text)
            tag.replace_with(text)
        return bs

# sensitive.py
from cleaner.plugin import BasePlugin
from collections import defaultdict

class SensitivePlugin(BasePlugin):
    name = "sensitive"
    priority = 30

    def __init__(self, word_path):
        self.trie = defaultdict(dict)
        with open(word_path, encoding="utf-8") as f:
            for w in f:
                w = w.strip()
                node = self.trie
                for c in w:
                    node = node.setdefault(c, {})
                node["#"] = True   # 结束符

    def _replace(self, text):
        result, i, n = [], 0, len(text)
        while i < n:
            node, start = self.trie, i
            j = i
            while j < n and text[j] in node:
                node = node[text[j]]
                j += 1
                if "#" in node:
                    result.append("*" * (j - start))
                    i = j
                    break
            else:
                result.append(text[i])
                i += 1
        return "".join(result)

    def clean(self, bs, context):
        for tag in bs.find_all(text=True):
            tag.replace_with(self._replace(tag.string or ""))
        return bs
  1. 对外接口(api.py)
from cleaner.engine import PipelineEngine
import os, functools

engine = PipelineEngine(os.getenv("BS_PIPELINE_CFG", "config/pipeline.yaml"))
clean = functools.lru_cache(maxsize=1024)(engine.clean)
  1. 使用方式
from cleaner.api import clean
html = "<html>臺灣  </html>"
print(clean(html))  # 输出:<html>台湾 </html>
  1. 热加载与回滚(生产扩展)
  • 使用 watchdog 监听配置文件,哈希变化后重新实例化 PipelineEngine;
  • 每次清洗前把原始 HTML 写入 backup/{uuid}.html,失败时根据签名回滚;
  • 通过 GitLab CI 将插件仓库打成 wheel,私有 PyPI 自动升级,实现版本化发布。

拓展思考

  1. 规则可视化:基于 Vue + Ant Design 搭建“清洗规则市场”,运营人员拖拽生成配置,后端自动生成 YAML,10 分钟上线新规则。
  2. 性能极限:当单条 HTML 大于 2 MB 时,可改用 lxml.iterparse 流式解析,结合 multiprocessing.shared_memory 做零拷贝,单核 QPS 从 800 提到 3500。
  3. 数据血缘:在 context 中注入 rule_trace,记录每个插件对 DOM 的 diff,写入 Apache Atlas,实现字段级血缘追踪,方便审计。
  4. 与 Scrapy 集成:实现 scrapy.downloadermiddlewares.DownloaderMiddleware,在 process_response 阶段直接调用 clean,下游 Spider 拿到的是已清洗的 response.text,业务代码零感知。
  5. 国产化替代:若公司禁用开源 PyPI,可将插件协议抽象为 gRPC,清洗逻辑下沉到 Go 微服务,Python 端只保留 Beautiful Soup 解析壳,满足信创要求。