Logoclaudeskills文档

Webapp Testing

基于 Playwright 的 Web 应用测试技能手册,包含服务器编排辅助脚本与故障排查提示。

来源:基于 anthropics/skills(MIT)内容改写。

要测试本地 Web 应用,请编写原生 Python Playwright 脚本。

可用辅助脚本

  • scripts/with_server.py —— 管理服务器生命周期(支持多服务)

务必先使用 --help 运行脚本 了解参数。除非确有必要定制,否则不要阅读源码,以免占用上下文窗口。脚本体量较大,设计为黑盒调用。

决策树:选择测试路径

用户任务 -> 是静态 HTML 吗?
    是 -> 直接读取 HTML 寻找选择器
            成功 -> 编写 Playwright 脚本
            失败/不完整 -> 当作动态应用处理(下方)

    否(动态 Web 应用) -> 服务器是否已启动?
        否 -> 运行 python scripts/with_server.py --help
              使用辅助脚本 + 编写精简 Playwright 脚本

        是 -> “先侦察再操作”流程:
            1. 导航并等待 networkidle
            2. 截图或查看 DOM
            3. 从渲染状态中确认选择器
            4. 使用这些选择器执行操作

示例:使用 with_server.py

先执行 --help 查看参数,然后启动服务器:

单个服务器:

python scripts/with_server.py --server "npm run dev" --port 5173 -- python your_automation.py

多个服务器(如后端 + 前端):

python scripts/with_server.py \
  --server "cd backend && python server.py" --port 3000 \
  --server "cd frontend && npm run dev" --port 5173 \
  -- python your_automation.py

自动化脚本仅需包含 Playwright 逻辑,服务器会自动管理:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto('http://localhost:5173')
    page.wait_for_load_state('networkidle')  # 关键:等待 JS 执行完成
    # ... 自动化逻辑 ...
    browser.close()

“先侦察再操作”模式

  1. 检查渲染后的 DOM:
    page.screenshot(path='/tmp/inspect.png', full_page=True)
    content = page.content()
    page.locator('button').all()
  2. 从结果中识别选择器
  3. 使用选择器执行操作

常见陷阱

  • 不要 在动态应用中等待 networkidle 前就检查 DOM
  • 务必 使用 page.wait_for_load_state('networkidle')

最佳实践

  • scripts/ 中的脚本视为黑盒,先 --help 查看用法再直接调用
  • 使用 sync_playwright() 编写同步脚本
  • 结束后关闭浏览器实例
  • 选择描述性选择器:text=role=、CSS 或 ID
  • 根据需要添加等待:page.wait_for_selector()page.wait_for_timeout()

参考示例

examples/ 目录演示常见模式:

  • element_discovery.py:发现按钮、链接、输入框
  • static_html_automation.py:使用 file:// URL 自动化静态页面
  • console_logging.py:捕获浏览器控制台日志

GitHub 访问

在 GitHub 查看