mcpField
P
playwright

playwright

github.com/dashed测试与质量2541 次安装1 周前更新
代码仓库

关于 playwright

playwright 是用于网页测试和常见页面操作的浏览器自动化技能,使用 uv 运行 Python 脚本。它提供命令行脚本,用于导航、截图、提取内容、提交表单和执行 JavaScript。

主要功能

  1. 01浏览器导航与截图
  2. 02提取页面文本和链接
  3. 03填写并提交表单
  4. 04执行 JavaScript
  5. 05捕获调试跟踪

适用场景

  1. 01截取网页画面
  2. 02提取页面内容和链接
  3. 03自动填写登录等表单
  4. 04使用跟踪记录调试浏览器自动化

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dashed/claude-marketplace --skill playwright

安装后在 Claude Code 中输入/playwright确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
api-reference.md
custom-scripts.md
selectors.md
troubleshooting.md

详细介绍

Playwright 浏览器自动化

概述

Playwright 支持浏览器自动化,可用于 Web 测试、截图、填写表单和抓取数据。此技能使用 Python 和 uv 编写独立脚本,无需全局安装。

前置条件

  • Python 3.10+
  • uv 包管理器
  • Playwright 浏览器二进制文件(一次性设置)

设置(仅首次)

Claude:不要直接运行浏览器安装命令。 请向用户建议这些命令,并让他们手动运行。这是一次性设置,将下载约 200MB 的浏览器二进制文件。

建议用户运行:

# Install Chromium (recommended, ~200MB)
uv run --with playwright playwright install chromium

# Or install all browsers
uv run --with playwright playwright install

验证安装:

uv run /path/to/plugins/playwright/scripts/check_setup.py

快速入门

截取任意 URL 的屏幕截图:

uv run /path/to/plugins/playwright/scripts/screenshot.py https://example.com

输出:/tmp/screenshot-{timestamp}.png

常见模式

截取屏幕截图
# Default (visible browser)
uv run scripts/screenshot.py https://example.com

# Full page, headless
uv run scripts/screenshot.py https://example.com --full-page --headless

# Custom output path
uv run scripts/screenshot.py https://example.com -o /tmp/my-shot.png
导航并提取内容
# Get page title and URL
uv run scripts/navigate.py https://example.com

# Extract all links as JSON
uv run scripts/navigate.py https://example.com --links

# Get page text content
uv run scripts/navigate.py https://example.com --text
填写并提交表单
uv run scripts/fill_form.py https://example.com/login \
  --field "[email protected]" \
  --field "password=secret123" \
  --submit
执行 JavaScript
uv run scripts/evaluate.py https://example.com "document.title"
uv run scripts/evaluate.py https://example.com "document.querySelectorAll('a').length"

编写自定义脚本

将此模板保存到 /tmp/my-automation.py:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = ["playwright==1.56.0"]
# ///
"""Custom Playwright automation script."""

import os
import sys
from playwright.sync_api import sync_playwright

HEADLESS = os.getenv("HEADLESS", "0").lower() in ("1", "true", "yes")

def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=HEADLESS)
        page = browser.new_page()

        try:
            page.goto("https://example.com")
            print(f"Title: {page.title()}")

            # Use semantic locators (preferred)
            page.get_by_role("button", name="Submit").click()
            page.get_by_label("Email").fill("[email protected]")

            # Screenshot
            page.screenshot(path="/tmp/result.png")

        except Exception as e:
            page.screenshot(path="/tmp/error.png")
            print(f"Error: {e}", file=sys.stderr)
            return 1
        finally:
            browser.close()

    return 0

if __name__ == "__main__":
    sys.exit(main())

运行命令:

uv run /tmp/my-automation.py

现代定位器 API

优先使用语义定位器,而非 CSS 选择器:

# PREFERRED: Semantic locators (accessible, stable)
page.get_by_role("button", name="Submit").click()
page.get_by_label("Email").fill("[email protected]")
page.get_by_placeholder("Search...").fill("query")
page.get_by_text("Welcome back").wait_for()
page.get_by_test_id("submit-btn").click()

# AVOID: Raw CSS selectors (fragile)
page.locator("button.btn-primary").click()  # Don't use

组合定位器:

# OR: Match either
page.get_by_role("button", name="New").or_(
    page.get_by_text("Create")
).click()

# Filter: Narrow down
page.locator("tr").filter(has_text="Active").first.click()

快速参考

操作代码
导航page.goto("https://url")
点击page.get_by_role("button", name="X").click()
填写输入框page.get_by_label("Email").fill("value")
获取文本page.get_by_role("heading").text_content()
屏幕截图page.screenshot(path="/tmp/shot.png")
等待page.get_by_text("Loaded").wait_for()
执行 JSpage.evaluate("document.title")

环境变量

变量描述默认值
HEADLESS以无头模式运行浏览器0(有头模式)
SLOW_MO减慢操作速度(ms)0
VIEWPORT浏览器视口1280x720
TRACE启用跟踪0(关闭)

示例:

HEADLESS=1 SLOW_MO=250 uv run scripts/screenshot.py https://example.com

使用跟踪进行调试

启用跟踪以调试复杂的自动化:

context.tracing.start(screenshots=True, snapshots=True, sources=True)
# ... your automation ...
context.tracing.stop(path="/tmp/trace.zip")

查看跟踪:

uv run --with playwright playwright show-trace /tmp/trace.zip

故障排除

“未找到浏览器”

建议用户安装浏览器二进制文件(不要直接运行):

uv run --with playwright playwright install chromium
“等待元素超时”

使用恰当的等待策略:

# Wait for element to be visible
page.get_by_text("Loaded").wait_for(state="visible")

# Wait for network idle
page.goto(url, wait_until="networkidle")
“元素无法交互”

确保元素可见,并将其滚动到视口中:

element = page.get_by_role("button", name="Submit")
element.scroll_into_view_if_needed()
element.click()
无头模式问题

使用有头模式进行调试:

HEADLESS=0 uv run scripts/screenshot.py https://example.com
容器/CI 问题

使用以下 Chromium 标志:

browser = p.chromium.launch(
    headless=True,
    args=["--disable-dev-shm-usage", "--no-sandbox"]
)

高级用法

如需完整文档,请参阅:

评论

支持 Markdown