mcpField
P
Playwright Browser Automation

Playwright Browser Automation

github.com/ovachieverテスト・品質56226 回インストール48 週間前に更新
リポジトリ

Playwright Browser Automation について

Playwright Browser Automationは、ブラウザー操作やWebテスト向けにPlaywrightスクリプトを作成・実行するスキルです。ローカル開発サーバーを先に検出し、生成したテストスクリプトは /tmp に置きます。

主な機能

  1. 01ローカル開発サーバーの検出
  2. 02タスク別Playwrightスクリプトの作成
  3. 03run.js経由でのスクリプト実行
  4. 04デフォルトで可視ブラウザーを使用
  5. 05safe clickなどのヘルパー

活用シーン

  1. 01複数の画面幅でページを確認
  2. 02ログインやフォーム操作の自動テスト
  3. 03リンク切れの検出
  4. 04スクリーンショットや要素の確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/ovachiever/droid-tings --skill playwright-browser-automation

インストール後、Claude Code で/playwright-browser-automationを入力して読み込まれたか確認します。

同梱ファイルpackage.jsonrun.js

詳細

重要 - パスの解決: このスキルはさまざまな場所(プラグインシステム、手動インストール、グローバル、プロジェクト固有)にインストールできます。コマンドを実行する前に、この SKILL.md ファイルを読み込んだ場所に基づいてスキルのディレクトリを特定し、以下のすべてのコマンドでそのパスを使用してください。$SKILL_DIR を実際に特定したパスに置き換えてください。

一般的なインストール先:

  • プラグインシステム:~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill
  • 手動でのグローバルインストール:~/.claude/skills/playwright-skill
  • プロジェクト固有:<project>/.claude/skills/playwright-skill

Playwright ブラウザー自動化

汎用的なブラウザー自動化スキルです。ご依頼の自動化タスクに合わせてカスタムの Playwright コードを作成し、ユニバーサルエグゼキューターで実行します。

重要なワークフロー - 次の手順を順番に実行してください:

  1. 開発サーバーを自動検出する - localhost のテストでは、必ず最初にサーバーを検出してください:

    cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(servers => console.log(JSON.stringify(servers)))"
    
    • サーバーが1つ見つかった場合:自動的に使用し、ユーザーに知らせます
    • 複数のサーバーが見つかった場合:どれをテストするかユーザーに尋ねます
    • サーバーが見つからない場合:URL を尋ねるか、開発サーバーの起動を支援することを提案します
  2. スクリプトを /tmp に書き込む - テストファイルをスキルのディレクトリに書き込まないでください。必ず /tmp/playwright-test-*.js を使用します

  3. デフォルトでブラウザーを表示する - ユーザーがヘッドレスモードを明示的に希望しない限り、常に headless: false を使用します

  4. URL をパラメーター化する - 常に、スクリプトの先頭にある環境変数または定数で URL を設定できるようにします

仕組み

  1. テストまたは自動化したい内容を説明します
  2. 実行中の開発サーバーを自動検出します(外部サイトのテストの場合は URL を尋ねます)
  3. カスタムの Playwright コードを /tmp/playwright-test-*.js に書き込みます(プロジェクト内が散らかることはありません)
  4. 次のコマンドで実行します:cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js
  5. 結果がリアルタイムで表示され、デバッグ用にブラウザーウィンドウも表示されます
  6. テストファイルは OS によって /tmp から自動的にクリーンアップされます

セットアップ(初回のみ)

cd $SKILL_DIR
npm run setup

Playwright と Chromium ブラウザーをインストールします。一度だけ実行すれば十分です。

実行パターン

ステップ 1:開発サーバーを検出する(localhost のテスト用)

cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(s => console.log(JSON.stringify(s)))"

ステップ 2:URL パラメーターを指定して、テストスクリプトを /tmp に書き込む

// /tmp/playwright-test-page.js
const { chromium } = require('playwright');

// Parameterized URL (detected or user-provided)
const TARGET_URL = 'http://localhost:3001'; // <-- Auto-detected or from user

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  await page.goto(TARGET_URL);
  console.log('Page loaded:', await page.title());

  await page.screenshot({ path: '/tmp/screenshot.png', fullPage: true });
  console.log('📸 Screenshot saved to /tmp/screenshot.png');

  await browser.close();
})();

ステップ 3:スキルのディレクトリから実行する

cd $SKILL_DIR && node run.js /tmp/playwright-test-page.js

よく使うパターン

ページをテストする(複数のビューポート)
// /tmp/playwright-test-responsive.js
const { chromium } = require('playwright');

const TARGET_URL = 'http://localhost:3001'; // Auto-detected

(async () => {
  const browser = await chromium.launch({ headless: false, slowMo: 100 });
  const page = await browser.newPage();

  // Desktop test
  await page.setViewportSize({ width: 1920, height: 1080 });
  await page.goto(TARGET_URL);
  console.log('Desktop - Title:', await page.title());
  await page.screenshot({ path: '/tmp/desktop.png', fullPage: true });

  // Mobile test
  await page.setViewportSize({ width: 375, height: 667 });
  await page.screenshot({ path: '/tmp/mobile.png', fullPage: true });

  await browser.close();
})();
ログインフローをテストする
// /tmp/playwright-test-login.js
const { chromium } = require('playwright');

const TARGET_URL = 'http://localhost:3001'; // Auto-detected

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  await page.goto(`${TARGET_URL}/login`);

  await page.fill('input[name="email"]', '[email protected]');
  await page.fill('input[name="password"]', 'password123');
  await page.click('button[type="submit"]');

  // Wait for redirect
  await page.waitForURL('**/dashboard');
  console.log('✅ Login successful, redirected to dashboard');

  await browser.close();
})();
フォームに入力して送信する
// /tmp/playwright-test-form.js
const { chromium } = require('playwright');

const TARGET_URL = 'http://localhost:3001'; // Auto-detected

(async () => {
  const browser = await chromium.launch({ headless: false, slowMo: 50 });
  const page = await browser.newPage();

  await page.goto(`${TARGET_URL}/contact`);

  await page.fill('input[name="name"]', 'John Doe');
  await page.fill('input[name="email"]', '[email protected]');
  await page.fill('textarea[name="message"]', 'Test message');
  await page.click('button[type="submit"]');

  // Verify submission
  await page.waitForSelector('.success-message');
  console.log('✅ Form submitted successfully');

  await browser.close();
})();
リンク切れを確認する
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  await page.goto('http://localhost:3000');

  const links = await page.locator('a[href^="http"]').all();
  const results = { working: 0, broken: [] };

  for (const link of links) {
    const href = await link.getAttribute('href');
    try {
      const response = await page.request.head(href);
      if (response.ok()) {
        results.working++;
      } else {
        results.broken.push({ url: href, status: response.status() });
      }
    } catch (e) {
      results.broken.push({ url: href, error: e.message });
    }
  }

  console.log(`✅ Working links: ${results.working}`);
  console.log(`❌ Broken links:`, results.broken);

  await browser.close();
})();
エラー処理付きでスクリーンショットを撮る
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  try {
    await page.goto('http://localhost:3000', {
      waitUntil: 'networkidle',
      timeout: 10000
    });

    await page.screenshot({
      path: '/tmp/screenshot.png',
      fullPage: true
    });

    console.log('📸 Screenshot saved to /tmp/screenshot.png');
  } catch (error) {
    console.error('❌ Error:', error.message);
  } finally {
    await browser.close();
  }
})();
レスポンシブデザインをテストする
// /tmp/playwright-test-responsive-full.js
const { chromium } = require('playwright');

const TARGET_URL = 'http://localhost:3001'; // Auto-detected

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  const viewports = [
    { name: 'Desktop', width: 1920, height: 1080 },
    { name: 'Tablet', width: 768, height: 1024 },
    { name: 'Mobile', width: 375, height: 667 }
  ];

  for (const viewport of viewports) {
    console.log(`Testing ${viewport.name} (${viewport.width}x${viewport.height})`);

    await page.setViewportSize({
      width: viewport.width,
      height: viewport.height
    });

    await page.goto(TARGET_URL);
    await page.waitForTimeout(1000);

    await page.screenshot({
      path: `/tmp/${viewport.name.toLowerCase()}.png`,
      fullPage: true
    });
  }

  console.log('✅ All viewports tested');
  await browser.close();
})();

インライン実行(簡単なタスク)

手早く一度だけ実行するタスクでは、ファイルを作成せずにコードをインラインで実行できます:

# Take a quick screenshot
cd $SKILL_DIR && node run.js "
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto('http://localhost:3001');
await page.screenshot({ path: '/tmp/quick-screenshot.png', fullPage: true });
console.log('Screenshot saved');
await browser.close();
"

インライン実行とファイル作成の使い分け:

  • インライン実行:一度だけの簡単なタスク(スクリーンショット、要素の有無の確認、ページタイトルの取得)
  • ファイル作成:複雑なテスト、レスポンシブデザインのチェック、ユーザーが再実行する可能性のあるタスク

利用可能なヘルパー

lib/helpers.js にオプションのユーティリティ関数があります:

const helpers = require('./lib/helpers');

// Detect running dev servers (CRITICAL - use this first!)
const servers = await helpers.detectDevServers();
console.log('Found servers:', servers);

// Safe click with retry
await helpers.safeClick(page, 'button.submit', { retries: 3 });

// Safe type with clear
await helpers.safeType(page, '#username', 'testuser');

// Take timestamped screenshot
await helpers.takeScreenshot(page, 'test-result');

// Handle cookie banners
await helpers.handleCookieBanner(page);

// Extract table data
const data = await helpers.extractTableData(page, 'table.results');

一覧については lib/helpers.js を参照してください。

高度な使い方

Playwright API の詳細なドキュメントについては、API_REFERENCE.md を参照してください:

  • セレクターとロケーターのベストプラクティス
  • ネットワークのインターセプトと API のモック
  • 認証とセッション管理
  • ビジュアルリグレッションテスト
  • モバイルデバイスのエミュレーション
  • パフォーマンステスト
  • デバッグ手法
  • CI/CD との統合

ヒント

  • 重要:最初にサーバーを検出する - localhost のテスト用コードを書く前に、必ず detectDevServers() を実行してください
  • テストファイルには /tmp を使用する - /tmp/playwright-test-*.js に書き込み、スキルディレクトリやユーザーのプロジェクトには書き込まないでください
  • URL をパラメーター化する - 検出または指定した URL を、各スクリプトの先頭にある TARGET_URL 定数に設定してください
  • デフォルト:ブラウザーを表示する - ユーザーからヘッドレスモードを明示的に指定されない限り、必ず headless: false を使用してください
  • ヘッドレスモード - ユーザーが「headless」または「background」での実行を明示的にリクエストした場合のみ、headless: true を使用してください
  • 速度を落とす: アクションを表示し、追いやすくするために、slowMo: 100 を使用してください
  • 待機方法: 固定タイムアウトではなく、waitForURL、waitForSelector、waitForLoadState を使用してください
  • エラー処理: 堅牢な自動化のために、必ず try-catch を使用してください
  • コンソール出力: 進行状況を追跡し、実行中の内容を表示するために、console.log() を使用してください

トラブルシューティング

Playwright がインストールされていない場合:

cd $SKILL_DIR && npm run setup

モジュールが見つからない場合: run.js ラッパーを介して、スキルディレクトリから実行していることを確認してください

ブラウザーが開かない場合: headless: false に設定されていることと、ディスプレイが利用可能であることを確認してください

要素が見つからない場合: 待機処理を追加してください:await page.waitForSelector('.element', { timeout: 10000 })

使用例

User: "Test if the marketing page looks good"

Claude: I'll test the marketing page across multiple viewports. Let me first detect running servers...
[Runs: detectDevServers()]
[Output: Found server on port 3001]
I found your dev server running on http://localhost:3001

[Writes custom automation script to /tmp/playwright-test-marketing.js with URL parameterized]
[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-marketing.js]
[Shows results with screenshots from /tmp/]
User: "Check if login redirects correctly"

Claude: I'll test the login flow. First, let me check for running servers...
[Runs: detectDevServers()]
[Output: Found servers on ports 3000 and 3001]
I found 2 dev servers. Which one should I test?
- http://localhost:3000
- http://localhost:3001

User: "Use 3001"

[Writes login automation to /tmp/playwright-test-login.js]
[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-login.js]
[Reports: ✅ Login successful, redirected to /dashboard]

注意事項

  • 各自動化は、リクエストに合わせて個別に作成されます
  • あらかじめ用意されたスクリプトに限らず、あらゆるブラウザータスクを実行できます
  • 実行中の開発サーバーを自動検出するため、URL をハードコードする必要はありません
  • テストスクリプトは自動クリーンアップのため /tmp に書き込まれます(ファイルが散らかりません)
  • run.js を介した適切なモジュール解決により、コードを確実に実行できます
  • 段階的な開示:高度な機能が必要な場合にのみ、API_REFERENCE.md が読み込まれます

コメント