蓝色天空网mbsky.com · 知识 · 实践 · 创造Playwright · 本地阅读预览
教程 / AI / 智能开发 / Playwright

Playwright 网络拦截

核对 Playwright page.route()/context.route() 匹配模式、abort 阻断、fulfill 模拟 JSON 与异常响应、continue 修改请求、fetch 篡改响应及 HAR 回放实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

网络拦截原理与 page.route() 匹配模式

网络拦截允许测试代码在浏览器发出 HTTP 请求时主动介入:可以阻断非关键资源、构造离线模拟响应,或在转发前后改写请求与响应内容,从而让前端测试摆脱对外部接口或脆弱测试环境的依赖。

核心入口为 `page.route(url, handler)`,用于注册拦截规则。目标匹配模式支持四种写法:精确完整 URL、Glob 通配符(如 `'**/api/**'` 或 `'**/*.{png,jpg,jpeg}'`,其中 `**` 匹配任意层级路径)、正则表达式,以及自定义判断函数。只要页面发出的请求命中模式,便会交由 `handler` 决定放行、阻断还是模拟返回。

route.abort() 阻断与 route.fulfill() 响应模拟

调用 `route.abort()` 可直接中止匹配请求,常用于屏蔽图片、第三方统计脚本或样式文件以加快功能测试加载。本站离线在本地服务上分别用 Glob(`**/*.{png,jpg,jpeg}`)、正则(`.*analytics\.js$`)与函数(`url.endswith('.css')`)阻断三类资源,实测 `requestfailed` 捕获到 `['analytics.js', 'pixel.png', 'style.css']`,页面样式未变红且统计脚本标志保持未加载。

`route.fulfill()` 是构造 Mock 数据的主力方法,可直接返回任意状态码、响应头与 JSON 数据。它既能为列表页注入可控测试样本,也能轻松模拟 `500` 等服务端异常以验证前端容错提示。本站离线拦截本地 `/api/users` 返回 2 条模拟用户(HTTP `200`),并拦截 `/api/data` 返回 HTTP `500` 与 `{"error": "服务器内部错误"}`,页面 `fetch` 均准确拿到预期状态与正文。

route.continue() 改写请求与 route.fetch() 改写响应

若希望请求继续抵达真实服务器但附加额外信息,可使用 `route.continue()`(Python API 为 `route.continue_()`)在放行前注入自定义请求头或改写 POST 请求体。本站离线拦截 `/api/echo` 追加请求头 `X-Custom-Header: MBSKY-TEST` 并在 POST JSON 中注入 `mode: 'test'`,本地服务端完整回显了修改后的 Header 与 Body。

需要保留真实接口数据结构而仅微调个别字段时,可在处理函数中先调用 `route.fetch()` 获取真实响应,再修改解析后的 JSON 并交由 `route.fulfill()` 返回给页面。本站离线对本地 `/api/products` 发起真实抓取,将首项商品名称由 `Original Item` 改为 `修改后的商品名` 后返回,前端既保留了真实 `id=1` 又渲染出改写后的标题。

Context 级作用域与 HAR 录制回放

`page.route()` 仅对当前标签页生效,而 `context.route()` 作用于同一浏览器上下文内的所有页面(含新开标签页)。本站实测在 Context 上阻断 `**/*.css` 后,同上下文打开的两个页面样式均同步被拦截。

当页面涉及大量或复杂的接口交互时,可借助 HAR(HTTP Archive)文件一次性录制真实流量(例如命令行 `npx playwright open --save-har=...` 或上下文 `record_har_path`),后续测试调用 `page.routeFromHAR()`(Python 为 `page.route_from_har()`)直接离线回放。本站离线先录制本地 `/api/products` 为 HAR 文件,再在新上下文启用 `route_from_har()` 访问:页面准确收到 `Original Item` 响应,同时本地服务端接口命中增量严格为 `0`(完全由 HAR 离线响应)。

page.route() 支持的 URL 匹配模式

模式示例说明
完整 URL`'https://api.example.com/users'`字符串精确匹配目标请求地址
Glob 通配符`'**/api/**'``*` 匹配单段,` ** ` 匹配跨层级任意路径
正则表达式`/\/api\/v\d\/users/`使用正则灵活匹配带版本号或动态参数的 URL
函数`url => url.includes('/api/')`以编程谓词函数按任意自定义条件决定是否拦截

Page 级拦截与 Context 级拦截对比

方式作用范围适用场景
`page.route()`仅当前单个 Page 实例单页面专用的局部接口 Mock 或异常注入
`context.route()`同一 BrowserContext 下的全部页面与弹窗多页面共享的全局资源阻断或统一 API 规则

运行路由阻断、JSON/500 模拟、请求改写、真实响应篡改及 HAR 离线回放实测

python · 阅读源码
"""Offline Playwright Chromium lab for Chapter 27: Network Interception & Mock."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import base64
import json
import os
from pathlib import Path
import re
import tempfile
import threading
from playwright.sync_api import sync_playwright


PIXEL_PNG = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
)

APP_HTML = """<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Network Mock Demo</title>
  <link rel="stylesheet" href="/style.css" />
  <script src="/analytics.js"></script>
</head>
<body>
  <img id="pic" src="/pixel.png" alt="pixel" />
  <div id="output">ready</div>
</body>
</html>"""


class MockHandler(BaseHTTPRequestHandler):
    product_hits = 0

    def log_message(self, fmt, *args):
        pass

    def _send(self, code, body, ctype="text/html; charset=utf-8"):
        data = body.encode("utf-8") if isinstance(body, str) else body
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/app":
            self._send(200, APP_HTML)
        elif self.path == "/style.css":
            self._send(200, "body { color: rgb(255, 0, 0); }", "text/css")
        elif self.path == "/pixel.png":
            self._send(200, PIXEL_PNG, "image/png")
        elif self.path == "/analytics.js":
            self._send(200, "window.__analyticsLoaded = true;", "application/javascript")
        elif self.path == "/api/products":
            MockHandler.product_hits += 1
            self._send(200, json.dumps({"items": [{"id": 1, "name": "Original Item"}]}), "application/json")
        else:
            self._send(404, "not found", "text/plain")

    def do_POST(self):
        if self.path == "/api/echo":
            length = int(self.headers.get("Content-Length", "0"))
            raw = self.rfile.read(length).decode("utf-8") or "{}"
            body = json.loads(raw)
            self._send(
                200,
                json.dumps({
                    "header": self.headers.get("X-Custom-Header", ""),
                    "body": body,
                }),
                "application/json",
            )
        else:
            self._send(404, "not found", "text/plain")


def launch_chromium(p):
    if os.path.exists(p.chromium.executable_path):
        return p.chromium.launch(headless=True)
    for ch in ("chrome", "msedge"):
        try:
            return p.chromium.launch(channel=ch, headless=True)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


def main():
    server = ThreadingHTTPServer(("127.0.0.1", 0), MockHandler)
    port = server.server_address[1]
    base = f"http://127.0.0.1:{port}"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with tempfile.TemporaryDirectory() as tmpdir:
            har_path = Path(tmpdir) / "api-responses.har"
            with sync_playwright() as p:
                browser = launch_chromium(p)
                try:
                    # Case 1: route.abort() with glob, regex, and predicate matchers
                    ctx1 = browser.new_context(base_url=base)
                    pg1 = ctx1.new_page()
                    aborted = []
                    pg1.on("requestfailed", lambda req: aborted.append(Path(req.url.split("?")[0]).name))
                    pg1.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
                    pg1.route(re.compile(r".*analytics\.js$"), lambda route: route.abort())
                    pg1.route(lambda url: url.endswith(".css"), lambda route: route.abort())
                    pg1.goto("/app")
                    body_color = pg1.evaluate("() => getComputedStyle(document.body).color")
                    analytics_flag = pg1.evaluate("() => Boolean(window.__analyticsLoaded)")
                    ctx1.close()
                    cases.append(make_case(
                        "route_abort_patterns",
                        {
                            "aborted_sorted": ["analytics.js", "pixel.png", "style.css"],
                            "css_not_red": True,
                            "analytics_blocked": True,
                        },
                        {
                            "aborted_sorted": sorted(aborted),
                            "css_not_red": body_color != "rgb(255, 0, 0)",
                            "analytics_blocked": not analytics_flag,
                        },
                    ))

                    # Case 2: route.fulfill() mocking 200 JSON and 500 error responses
                    ctx2 = browser.new_context(base_url=base)
                    pg2 = ctx2.new_page()
                    pg2.route(
                        "**/api/users",
                        lambda route: route.fulfill(
                            status=200,
                            content_type="application/json",
                            body=json.dumps([{"id": 1, "name": "alice"}, {"id": 2, "name": "bob"}]),
                        ),
                    )
                    pg2.route(
                        "**/api/data",
                        lambda route: route.fulfill(
                            status=500,
                            content_type="application/json",
                            body=json.dumps({"error": "服务器内部错误"}),
                        ),
                    )
                    pg2.goto("/app")
                    users_res = pg2.evaluate("async () => { const r = await fetch('/api/users'); return {status: r.status, count: (await r.json()).length}; }")
                    err_res = pg2.evaluate("async () => { const r = await fetch('/api/data'); return {status: r.status, error: (await r.json()).error}; }")
                    ctx2.close()
                    cases.append(make_case(
                        "route_fulfill_json_and_error",
                        {"users_status": 200, "users_count": 2, "err_status": 500, "err_msg": "服务器内部错误"},
                        {
                            "users_status": users_res["status"],
                            "users_count": users_res["count"],
                            "err_status": err_res["status"],
                            "err_msg": err_res["error"],
                        },
                    ))

                    # Case 3: route.continue_() modifying request headers and POST JSON body
                    ctx3 = browser.new_context(base_url=base)
                    pg3 = ctx3.new_page()

                    def modify_echo(route, request):
                        headers = {**request.headers, "x-custom-header": "MBSKY-TEST"}
                        payload = json.loads(request.post_data or "{}")
                        payload["mode"] = "test"
                        route.continue_(headers=headers, post_data=json.dumps(payload))

                    pg3.route("**/api/echo", modify_echo)
                    pg3.goto("/app")
                    echo_res = pg3.evaluate("""async () => {
                        const r = await fetch('/api/echo', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({user: 'alice'})
                        });
                        return r.json();
                    }""")
                    ctx3.close()
                    cases.append(make_case(
                        "route_continue_modify_headers_and_post",
                        {"header": "MBSKY-TEST", "body": {"user": "alice", "mode": "test"}},
                        echo_res,
                    ))

                    # Case 4: route.fetch() fetching real backend response then patching JSON
                    ctx4 = browser.new_context(base_url=base)
                    pg4 = ctx4.new_page()

                    def patch_products(route):
                        resp = route.fetch()
                        data = resp.json()
                        data["items"][0]["name"] = "修改后的商品名"
                        route.fulfill(status=resp.status, content_type="application/json", body=json.dumps(data))

                    pg4.route("**/api/products", patch_products)
                    pg4.goto("/app")
                    patched = pg4.evaluate("async () => (await fetch('/api/products')).json()")
                    ctx4.close()
                    cases.append(make_case(
                        "route_fetch_modify_real_response",
                        {"id": 1, "name": "修改后的商品名"},
                        patched["items"][0],
                    ))

                    # Case 5: context.route() multi-page scope + HAR record & route_from_har() replay
                    ctx5 = browser.new_context(base_url=base)
                    ctx5.route("**/*.css", lambda route: route.abort())
                    p5a = ctx5.new_page()
                    p5b = ctx5.new_page()
                    p5a.goto("/app")
                    p5b.goto("/app")
                    both_uncolored = (
                        p5a.evaluate("() => getComputedStyle(document.body).color") != "rgb(255, 0, 0)"
                        and p5b.evaluate("() => getComputedStyle(document.body).color") != "rgb(255, 0, 0)"
                    )
                    ctx5.close()

                    # Record HAR
                    rec_ctx = browser.new_context(base_url=base, record_har_path=str(har_path), record_har_url_filter="**/api/products")
                    rec_pg = rec_ctx.new_page()
                    rec_pg.goto("/app")
                    rec_pg.evaluate("async () => (await fetch('/api/products')).json()")
                    rec_ctx.close()

                    hits_before_replay = MockHandler.product_hits
                    rep_ctx = browser.new_context(base_url=base)
                    rep_pg = rep_ctx.new_page()
                    rep_pg.route_from_har(str(har_path), url="**/api/products")
                    rep_pg.goto("/app")
                    replayed = rep_pg.evaluate("async () => (await fetch('/api/products')).json()")
                    rep_ctx.close()
                    hits_after_replay = MockHandler.product_hits

                    cases.append(make_case(
                        "context_route_and_har_replay",
                        {
                            "context_route_both_pages": True,
                            "har_replayed_name": "Original Item",
                            "server_hits_delta": 0,
                        },
                        {
                            "context_route_both_pages": both_uncolored,
                            "har_replayed_name": replayed["items"][0]["name"],
                            "server_hits_delta": hits_after_replay - hits_before_replay,
                        },
                    ))
                finally:
                    browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 Glob/正则/函数阻断 3 类资源、200/500 响应模拟、Header 与 POST Body 改写回显、route.fetch() 局部改写以及多页 context.route 与 HAR 零服务端命中回放。
运行路由阻断、JSON/500 模拟、请求改写、真实响应篡改及 HAR 离线回放实测

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:78bf09eb66813497db66d589325791a7eb1f571ae29eef13f58a00a5fc3121c8

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Playwright 网络拦截实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:d8fd6158da8fc4d3da748c88130674e3f5fdcaf11ccc077125e9f4869401227a

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

route.fulfill()、route.continue() 与 route.fetch() + route.fulfill() 三种模式分别适合什么测试场景?

展开参考解答

route.fulfill() 完全不发往后端,适合纯前端离线 Mock 与 500 异常模拟;route.continue() 用于向真实后端发请求前动态补充 Header 或改写提交负载;route.fetch() + route.fulfill() 则适合保留真实接口主体结构,仅覆写少量字段以制造边界场景。

规范与官方依据