Browser Automation Guide浏览器自动化指南

Claude Code Playwright MCP
Setup & Workflow
Claude Code 与 Playwright MCP
配置与工作流程

Connect Claude Code to a real browser through Playwright MCP, then build an inspect, act, and verify loop that stays observable and controlled.

通过 Playwright MCP 将 Claude Code 连接到真实浏览器,建立可观察、可控制的“检查—执行—验证”闭环。

Hand-drawn Claude Code and Playwright MCP browser automation workflow showing page inspection, one bounded action, and result verification

TL;DR核心摘要

Use MCP for exploration

Playwright MCP fits changing browser tasks that need persistent context, semantic page inspection, and iterative decisions.

Define the evidence first

State the final URL, visible text, saved value, screenshot, console result, or other observable proof before the run begins.

Work in checkpoints

Inspect the page, perform one bounded action, reacquire state, compare with the goal, and stop at approval boundaries.

Promote stable work

Move repeatable assertions into committed Playwright tests; keep MCP for discovery, diagnosis, and variable workflows.

用 MCP 做探索

Playwright MCP 适合页面路径会变化、需要持续上下文、语义检查和逐步决策的浏览器任务。

先定义证据

执行前先约定最终网址、可见文字、保存后的值、截图或控制台结果等可验证证据。

设置检查点

检查页面、执行一次边界明确的动作、重新获取状态、对照目标,并在审批边界暂停。

沉淀稳定流程

把可重复断言写成正式 Playwright 测试;MCP 继续承担探索、诊断和变化较多的工作流。

The strongest Claude Code + Playwright MCP workflow is not “let the agent browse until it finishes.” It is a sequence of observable contracts: establish the session, inspect the live page, make one permitted change, reacquire the page state, and compare direct evidence with a predefined success condition. This page focuses on that operating model; the separate Playwright MCP setup guide covers installation commands, scopes, connection checks, and removal.

Claude Code 与 Playwright MCP 的最佳用法,不是“让智能体一直浏览到自己认为完成”,而是建立一连串可观察的任务约定:创建会话、检查实时页面、执行一次获准操作、重新获取页面状态,再把直接证据与预先定义的成功条件对照。本页重点讲这种运行方式;安装命令、作用域、连接检查和卸载方法可查看单独的 Playwright MCP 配置指南

Set up Playwright MCP in Claude Code在 Claude Code 中配置 Playwright MCP

Decide whether MCP is the right interface先判断 MCP 是否适合这项任务

The official Playwright MCP repository distinguishes MCP from CLI-based browser work. MCP is useful when an agent benefits from persistent state, rich page introspection, and iterative reasoning across a changing interface. CLI or skill-based execution can be more context-efficient for coding agents that need concise, high-throughput commands. A committed Playwright test remains the better target when the path and assertions are already stable enough for CI.

官方 Playwright MCP 仓库已经区分 MCP 与 CLI 浏览器工作流。任务需要保持会话状态、深入读取页面结构,并在变化中的界面上反复判断时,MCP 更合适;如果编码智能体更看重简洁命令和上下文效率,CLI 或 skill 方式可能更轻;当执行路径与断言已经稳定、需要进入 CI 时,则应直接编写正式 Playwright 测试。

  • Choose MCP: exploratory debugging, unfamiliar interfaces, dynamic workflows, or tasks where the next action depends on the current page state.
  • Choose CLI or a skill: concise scripted operations where loading a broad MCP tool schema would add unnecessary context.
  • Choose a test: fixed prerequisites, selectors, assertions, and outputs that must run the same way on every build.
  • Choose manual review: legal interpretation, irreversible financial impact, sensitive personal data, or ambiguous visual judgment.
  • 选择 MCP:探索式调试、陌生界面、动态工作流,或下一步必须根据当前页面状态决定的任务。
  • 选择 CLI 或 skill:操作路径简洁明确,加载较大的 MCP 工具定义只会增加上下文负担。
  • 选择正式测试:前置条件、定位方式、断言和输出均已固定,需要每次构建以相同方式运行。
  • 选择人工处理:涉及法律判断、不可逆资金影响、敏感个人数据或模糊视觉判断。

Choose the session model before adding credentials接入凭据前先确定会话模式

Playwright MCP can use a persistent profile, an isolated context, supplied storage state, or a browser extension connected to an existing tab. Start with an isolated or disposable session for public-page tasks. Persistent profiles reduce repeated login work but retain cookies and local state, so use a dedicated account and profile rather than a personal daily browser. An existing-browser extension is convenient when the workflow depends on an already authenticated tab, yet it also exposes more unrelated session state and should be reserved for tightly scoped tasks.

Playwright MCP 可以使用持久化配置文件、隔离上下文、预先提供的 storage state,或通过浏览器扩展连接已有标签页。处理公开页面时,优先从隔离或一次性会话开始。持久化配置可以减少重复登录,但会保留 Cookie 和本地状态,因此应配合专用账号与专用配置使用,不要直接接管个人日常浏览器。扩展方式适合复用已经登录的标签页,但也会暴露更多无关会话状态,只应在任务范围非常清楚时采用。

Configure outputs around the evidence you need围绕验收证据配置输出

Do not enable every capability by default. Decide whether the task needs an accessibility snapshot, screenshot, console messages, network information, downloaded files, generated code, or a saved session. Set a controlled output directory if artifacts must be retained, define a viewport when visual evidence matters, and choose a console level that captures actionable failures without flooding the run. Add device emulation only when the outcome is genuinely viewport-specific.

不要默认开启所有能力。先判断任务究竟需要无障碍快照、截图、控制台信息、网络请求、下载文件、生成代码,还是保存完整会话。如果需要保留证据,应设置受控的输出目录;视觉验收需要固定视口;控制台级别要能捕获有效错误,同时避免无关日志淹没执行记录。只有结果确实与设备或视口相关时,才加入设备模拟。

Verify a clean baseline建立干净的基线

Before using accounts, ask Claude Code to open a public page and return the final URL, title, one heading, and one named control without changing anything. Then allow a single reversible navigation and request the new URL and heading. This proves that the server starts, the browser launches, the page snapshot is readable, tool calls return, and state can be refreshed. If any layer fails, stop there; adding authentication or more options only makes the fault harder to isolate.

在使用账号前,先让 Claude Code 打开公开页面,在不进行修改的情况下返回最终网址、页面标题、一个可见标题和一个具名控件;随后只允许一次可逆跳转,并要求返回新网址与标题。这样可以确认服务器进程、浏览器启动、页面快照、工具调用和状态刷新都正常。如果其中任何一层失败,应先停下来排查;此时继续加入登录状态或更多参数,只会让问题更难定位。

Use an inspect, act, and verify workflow采用“检查—执行—验证”工作流程

Turn the request into an observable contract把请求改写成可观察的任务约定

A browser prompt needs more than a goal. Include the starting URL, expected user-visible outcome, allowed domains, permitted actions, forbidden actions, review checkpoints, and proof of completion. “Update the webhook” is unsafe and hard to verify. “Open the staging settings page, identify the webhook form, populate these values, report every field, and stop before saving” gives Claude Code a stable objective and an explicit stopping point.

浏览器提示词不能只有一个目标,还要包含起始网址、用户可见的预期结果、允许域名、可执行动作、禁止事项、人工检查点和完成证据。“更新 Webhook”既不安全,也难以验收;“打开测试环境设置页,找到 Webhook 表单,填写这些值,报告所有字段,并在保存前停止”则给出了稳定目标和明确停止点。

Run a disciplined five-step loop执行严格的五步闭环

  • Orient: confirm the live URL, account or environment, page title, and whether a login wall, consent screen, or redirect changed the context.
  • Inspect: read the current accessibility snapshot and locate controls by role, visible name, label, or stable test ID.
  • Act: perform one bounded navigation, input, or click; do not chain speculative actions against an old snapshot.
  • Reacquire: after navigation, refresh, modal changes, frame changes, or dynamic updates, inspect the live page again.
  • Verify: compare the final URL and visible evidence with the success condition; report uncertainty instead of inferring success.
  • 确认环境:核对实时网址、账号或环境、页面标题,并检查登录墙、Cookie 同意页或重定向是否改变了上下文。
  • 检查页面:读取当前无障碍快照,通过角色、可见名称、标签或稳定测试 ID 定位控件。
  • 执行动作:一次只做一个边界明确的导航、输入或点击,不要基于旧快照连续猜测操作。
  • 重新获取:导航、刷新、弹窗、iframe 或动态内容变化后,再次检查实时页面。
  • 验证结果:将最终网址和可见证据与成功条件对照;无法确认时如实报告,不要推断成功。

Use different evidence for different browser jobs不同任务使用不同验收证据

Research needs the final source URL plus the exact page fields used in the answer. Bug reproduction needs the starting state, minimal action sequence, visible error, console output when relevant, and the state immediately before failure. Form preparation needs a field-by-field summary before submission. A saved setting needs both a success notification and a reload showing the persisted value. Visual review needs a defined viewport and the exact component state that must appear in the screenshot.

网页调研应保留最终来源网址,以及答案实际使用的页面字段;复现缺陷需要记录起始状态、最短操作序列、可见错误、必要的控制台信息和失败前状态;表单准备应在提交前逐字段汇总;保存设置后,既要看到成功提示,也要刷新页面确认数据仍然存在;视觉验收则要提前规定视口尺寸和截图中必须出现的组件状态。

Apply the loop to common development workflows把闭环应用到常见开发任务

For UI investigation, ask Claude Code to map the relevant controls and states before proposing a test. For bug reproduction, freeze the starting account and data, follow the shortest path, and stop at the first divergence. For content or settings work, split drafting from submission so a person can review the exact payload. For regression checks, let MCP discover selectors and states, then promote the stable path into a committed test rather than keeping a free-form browser prompt as the permanent artifact.

调查界面问题时,先让 Claude Code 梳理相关控件和状态,再提出测试方案;复现缺陷时,固定起始账号与数据,沿最短路径执行,并在第一次偏离预期的位置停止;处理内容或设置时,把“填写”与“提交”分开,让人工复核确切内容;构建回归检查时,可以先用 MCP 探索定位方式和状态,再把稳定路径写成正式测试,不要长期依赖自由形式的浏览器提示词。

Make every run produce a useful handoff让每次执行都能形成可用交接

A run should end with more than “done.” Ask for a compact record of the starting URL, environment, actions completed, actions intentionally skipped, approvals received, final URL, success evidence, unresolved uncertainty, and any artifact paths. When the outcome is a proposed change, include the exact value or payload awaiting approval. When the outcome is a defect, include the last expected state, first unexpected state, and the shortest known reproduction path. This makes the result reviewable by someone who did not watch the browser session.

一次执行结束时,不能只返回“已完成”。应给出简洁交接记录,包括起始网址、运行环境、已完成动作、主动跳过的动作、取得的授权、最终网址、成功证据、仍未确认的问题和相关产物路径。如果结果是一项待批准修改,要列出准备提交的准确值或内容;如果结果是缺陷,则要说明最后一个符合预期的状态、第一个异常状态,以及目前已知的最短复现路径。这样,即使没有旁观整个浏览器会话,其他人也能复核结果。

Define stopping conditions before the run as carefully as success conditions. Stop when the domain changes unexpectedly, the active account or environment is unclear, a prerequisite is missing, the page requests new permissions, the proposed payload differs from the approved value, evidence conflicts, or an action would cross from preparation into consequence. A clean stop with a precise reason is a successful control outcome—not a failed automation attempt.

停止条件应与成功条件一样在执行前定义清楚。出现意外域名跳转、无法确认当前账号或环境、缺少前置条件、页面请求新增权限、准备提交的内容与已批准值不一致、证据互相冲突,或操作即将从“准备”跨入“产生实际影响”时,都应停止。能够在边界处准确暂停并说明原因,本身就是控制机制成功,并不等于自动化失败。

Recover without repeating destructive actions恢复时不要重复高影响操作

If a control disappears, reacquire the page snapshot; the DOM may have changed or the control may have moved into a modal or frame. If an action times out, check whether navigation is still running, a popup opened, authentication expired, or a download started. Before retrying a submission, look for a confirmation message, changed URL, persisted value, or duplicate record. Preserve the last known state and the action that preceded the failure so the next attempt begins from evidence rather than guesswork.

控件消失后,应重新获取页面快照;DOM 可能已经变化,控件也可能进入弹窗或 iframe。操作超时后,要检查页面是否仍在导航、是否打开新窗口、登录是否失效,或下载是否已经开始。重复提交前,先查找确认提示、网址变化、已保存值或重复记录。保留最后一个已知状态和错误前的动作,让下一次尝试基于证据,而不是从头猜测。

Safety and debugging practices安全与调试实践

Separate observation, preparation, and consequence区分观察、准备与实际影响

Read-only inspection can usually proceed inside an approved domain. Reversible preparation—opening filters, drafting text, or filling an unsent form—should stop at a review checkpoint. Consequential actions require explicit approval immediately before execution: sending a message, publishing, placing an order, accepting legal terms, changing access, uploading private files, or deleting records. Ask for approval with the exact target and payload so the person can evaluate what will change.

在获准域名内进行只读检查通常可以直接继续;打开筛选器、起草内容或填写但不提交表单等可逆准备,应在复核点暂停;发送消息、发布、下单、接受法律条款、修改访问权限、上传私密文件或删除记录等高影响操作,则必须在执行前即时取得明确授权。审批提示需要写清目标对象和具体内容,让用户知道究竟会发生什么变化。

Treat browser state as a credential把浏览器状态当作凭据管理

  • Use a dedicated test account or profile instead of a personal daily-use browser.
  • Keep passwords, API keys, recovery codes, and raw cookies out of prompts, screenshots, and retained logs.
  • Prefer short-lived isolated sessions for unfamiliar sites or one-off work.
  • Review upload paths and download destinations by exact filename before transfer.
  • Close sessions and remove retained artifacts when the evidence is no longer needed.
  • 使用专用测试账号或配置文件,不要直接使用个人日常浏览器。
  • 密码、API Key、恢复码和原始 Cookie 不应出现在提示词、截图或长期日志中。
  • 陌生网站或一次性任务优先使用短期隔离会话。
  • 上传或下载前,按准确文件名检查来源路径和目标位置。
  • 证据不再需要后,关闭会话并清理留存的敏感产物。

Do not mistake origin filters for a security boundary不要把来源过滤当作完整安全边界

Playwright MCP documents allowed- and blocked-origin options, but its official configuration notes that an allowlist is not a security boundary and does not govern redirects. Use those settings to reduce accidental reach, not to replace account isolation, least privilege, workspace trust, and human approvals. Avoid unrestricted file access unless the task genuinely requires it, and do not disable browser sandboxing merely to bypass an unexplained startup error.

Playwright MCP 提供允许来源和阻止来源选项,但官方配置明确说明,允许列表并不构成安全边界,也无法约束重定向。这些设置可以减少误访问,却不能替代账号隔离、最小权限、工作区信任和人工审批。除非任务确实需要,否则不要开放无限制文件访问;也不要为了绕过原因不明的启动错误而随意关闭浏览器沙箱。

Where QVeris fits beside Playwright MCPQVeris 如何与 Playwright MCP 协同

The current QVeris catalog does not contain an exact Tool or Provider for configuring Playwright MCP in Claude Code. Following the relevance rule, this page links to QVeris Docs and the QVeris Playground instead of presenting a loosely related browser provider as an exact match.

当前 QVeris 目录中没有能够直接完成 Claude Code Playwright MCP 配置的精确 Tool 或 Provider。按照强相关原则,本页使用 QVeris 文档QVeris Playground,不会把弱相关浏览器供应商包装成精确匹配。

Use APIs for structured work and the browser for rendered state结构化工作交给 API,渲染状态交给浏览器

  • Use Playwright MCP when the task depends on rendered UI, authenticated page state, UI-only controls, or exploratory interaction.
  • Use QVeris when a verified API or tool can provide typed inputs, predictable outputs, and clearer failure handling without rendering a page.
  • Combine them when structured data is prepared or validated through an API, then entered or visually confirmed through the browser.
  • Keep human approval between prepared data and any browser action that creates an external consequence.
  • 任务依赖渲染后的界面、登录状态、界面专属控件或探索式交互时,使用 Playwright MCP。
  • 经过核验的 API 或工具能够以类型明确的输入、可预测输出和更清晰的错误处理完成任务时,使用 QVeris。
  • 也可以先通过 API 准备或校验结构化数据,再由浏览器录入或进行视觉确认。
  • 在已准备数据与会产生外部影响的浏览器操作之间,保留人工审批。

QVeris does not configure the local MCP server, manage the browser profile, or approve Claude Code tool calls. Its role begins when the broader workflow needs structured capabilities alongside UI automation. If an API already owns the operation, calling it directly is usually simpler than navigating a web page; if the rendered experience is the thing being tested, Playwright remains the correct layer.

QVeris 不负责配置本地 MCP 服务器、管理浏览器配置文件,也不会替用户批准 Claude Code 工具调用。只有当更完整的工作流需要在界面自动化之外调用结构化能力时,它才开始发挥作用。如果某项操作已经有正式 API,直接调用通常比网页导航更简单;如果验收对象就是渲染后的体验,Playwright 才是正确执行层。

FAQ常见问题

MCP, CLI, or a test?

Use MCP for persistent, exploratory interaction; CLI or skills for concise high-throughput operations; and committed tests for stable, repeatable assertions.

Can it reuse a login?

Yes, through a persistent profile, storage state, or an extension, but use a dedicated account and protect retained browser state like a credential.

Why did a locator expire?

Navigation or dynamic updates may have replaced the page structure. Take a fresh snapshot and locate the control again instead of retrying the old reference.

What proves success?

Use direct evidence: final URL, visible saved value, confirmation message plus reload, screenshot at a defined viewport, or relevant console and network output.

When should it stop?

Stop at uncertainty, a domain change, an unexpected login or consent screen, a failed prerequisite, or immediately before any consequential action.

When is an API better?

Prefer an API for typed, high-volume, unattended, or deterministic work. Keep the browser for UI-only operations and rendered-state evidence.

选择 MCP、CLI 还是测试?

持续性的探索交互用 MCP;追求简洁和高吞吐的操作用 CLI 或 skill;稳定且重复的断言写成正式测试。

可以复用登录状态吗?

可以使用持久化配置、storage state 或扩展,但应采用专用账号,并像管理凭据一样保护留存的浏览器状态。

为什么元素引用会失效?

导航或动态更新可能已经替换页面结构。应重新获取快照并再次定位控件,不要继续重试旧引用。

什么才算成功证据?

应采用直接证据,例如最终网址、页面显示的已保存值、成功提示加刷新验证、固定视口截图,或相关控制台与网络信息。

什么时候必须停止?

遇到结果不确定、域名变化、意外登录或同意页面、前置条件失败,或即将执行高影响操作时,都应暂停。

什么时候 API 更合适?

需要类型明确、批量、无人值守或确定性执行时,优先使用 API;浏览器只处理界面专属操作和渲染结果取证。

References and next steps参考资料与下一步

Playwright MCP repository
Claude Code MCP documentation

Playwright MCP 代码仓库
Claude Code MCP 文档