如何为Beautiful Soup数据提取函数编写有效的单元测试?

解读

在国内一线互联网公司的技术面试中,面试官提出“如何给 Beautiful Soup 的数据提取函数写单元测试”,并不是想听你背 pytest 语法,而是考察三层能力:

  1. 是否理解 BS4 的“容错+动态”特性——网页结构随时可能微调,测试必须“鲁棒”。
  2. 是否能把“爬虫不确定性”转化为“测试确定性”——用最小、可控、可复现的 HTML 片段代替真实网络 IO。
  3. 是否熟悉国内主流技术栈(pytest + requests-mock + GitLab-CI/阿里 Aone 流水线)的落地套路。
    回答时要把“测试策略 → 测试数据 → 断言技巧 → 持续集成”一口气讲清,并给出可直接粘贴跑的代码示例,才能拿到高分。

知识点

  1. 测试隔离:禁止访问外网,所有 HTML 用本地 fixture 文件或内联字符串。
  2. 双层断言:
    a. 数量断言——先锁定“能抓到几条”,防止 DOM 微调导致漏抓。
    b. 内容断言——再用正则/近似匹配,容忍空格、属性顺序变化。
  3. 异常分支:主动给残缺标签、编码异常、空文档,验证 BS4 的容错逻辑是否被业务代码正确透传。
  4. 参数化:pytest.mark.parametrize 覆盖“列表页”“详情页”“无结果页”三种典型结构。
  5. 性能兜底:用 pytest-timeout 限制单测 1 s 内跑完,防止死循环或链式选择器低效。
  6. 覆盖率卡点:国内项目普遍要求 diff 覆盖率 ≥90%,因此要把提取函数拆到单独模块,方便统计。
  7. 流水线集成:在 GitLab-CI 或阿里 Aone 的 .yml 里加 pytest --cov=extract --cov-report=xml,再把 xml 推送到 Sonar 做质量门禁。

答案

下面给出一套“可直接落地”的示例,假设业务函数叫 extract_house_price(html: str) -> List[Dict],目标是从链家二手房列表页提取“标题+价格”。

项目结构

bs4_project/
├── extract.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   ├── fixtures/
│   │   ├── lianjia_list.html
│   │   ├── lianjia_list_empty.html
│   │   └── lianjia_malformed.html
│   └── test_extract.py
└── requirements-test.txt

extract.py

from bs4 import BeautifulSoup
from typing import List, Dict

def extract_house_price(html: str) -> List[Dict]:
    soup = BeautifulSoup(html, "lxml")
    cards = soup.select("ul.sellListContent li.LOGCLICKDATA")
    result = []
    for node in cards:
        title_node = node.select_one("div.title a")
        price_node = node.select_one("div.totalPrice span")
        if not (title_node and price_node):
            continue
        result.append({
            "title": title_node.get_text(strip=True),
            "price": price_node.get_text(strip=True)
        })
    return result

tests/conftest.py

import pytest
from pathlib import Path

BASE = Path(__file__).with_suffix('')

@pytest.fixture(scope="session")
def load_fixture():
    def _loader(name):
        return (BASE / "fixtures" / name).read_text(encoding="utf-8")
    return _loader

tests/test_extract.py

import pytest
import re
from extract import extract_house_price

class TestExtractHousePrice:
    def test_normal_case(self, load_fixture):
        html = load_fixture("lianjia_list.html")
        data = extract_house_price(html)
        # 数量断言
        assert len(data) == 30
        # 内容断言:价格一定是“数字+万”
        for item in data:
            assert re.fullmatch(r"\d+\.?\d*万", item["price"])
            assert item["title"]

    def test_empty_list(self, load_fixture):
        html = load_fixture("lianjia_list_empty.html")
        assert extract_house_price(html) == []

    def test_malformed_html(self, load_fixture):
        html = load_fixture("lianjia_malformed.html")
        # BS4 会自动补全,但仍应无异常抛出
        assert isinstance(extract_house_price(html), list)

    @pytest.mark.parametrize("snippet,expected_len", [
        ("<ul class='sellListContent'></ul>", 0),
        ("<ul class='sellListContent'><li class='LOGCLICKDATA'><div class='title'><a>测试</a></div><div class='totalPrice'><span>100万</span></div></li></ul>", 1),
    ])
    def test_micro_fixture(self, snippet, expected_len):
        assert len(extract_house_price(snippet)) == expected_len

    def test_performance(self):
        from time import time
        big = "<ul>" + "<li class='LOGCLICKDATA'><div class='title'><a>标题</a></div><div class='totalPrice'><span>100万</span></div></li>" * 1000 + "</ul>"
        t0 = time()
        extract_house_price(big)
        assert time() - t0 < 1.0

运行命令

pip install -r requirements-test.txt   # pytest pytest-cov pytest-timeout beautifulsoup4 lxml
pytest tests/ -q --cov=extract --cov-report=term-missing --timeout=1

国内 GitLab-CI 模板(.gitlab-ci.yml 片段)

test:
  stage: test
  image: python:3.10
  script:
    - pip install -r requirements-test.txt
    - pytest --cov=extract --cov-report=xml --timeout=1
    - mv coverage.xml public/
  coverage: '/(?i)total.*?(\d+%)$/'
  artifacts:
    reports:
      coverage_report:
        file: public/coverage.xml
        format: cobertura

拓展思考

  1. 如果页面是 React 服务端渲染 + 懒加载,HTML 首屏只有占位符,单元测试应如何升级?
    答:把“提取函数”拆成两步:① 纯 BS4 提取可见骨架;② 用正则校验 JS 埋点数据(window.INITIAL_STATE)。测试时把“服务端返回的 HTML”与“前端补齐后的 JSON”分别做快照对比,既测 BS4 又测接口契约。

  2. 国内不少公司用 Puppeteer 做“预抓取”生成静态 HTML,如何让 BS4 单测与 Puppeteer 版本对齐?
    答:在 CI 里先生成“最新静态片段”→ 作为 fixture 覆盖旧文件 → 再跑 pytest。若断言失败,自动开 MR 提醒前端改结构,实现“结构变化即测试失败”的强制门禁。

  3. 当提取逻辑涉及“中文关键词归一化”(如“满五唯一”→“m5wy”),单测如何覆盖?
    答:把归一化函数拆成纯函数,单独测;BS4 层只负责抓原文。这样即使业务词典升级,也不会导致 BS4 用例大面积失效,符合“单一职责”与“测试金字塔”原则。