stagehand-automation
Stagehand v3とClaudeを活用し、AIでブラウザ操作を自動化することで、UI変更に強いテストやAIエージェント、動的なウェブ自動化などを構築するSkill。
📜 元の英語説明(参考)
AI-powered browser automation using Stagehand v3 and Claude. Use when building self-healing tests, AI agents, dynamic web automation, or when traditional selectors break frequently due to UI changes.
🇯🇵 日本人クリエイター向け解説
Stagehand v3とClaudeを活用し、AIでブラウザ操作を自動化することで、UI変更に強いテストやAIエージェント、動的なウェブ自動化などを構築するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o stagehand-automation.zip https://jpskill.com/download/9498.zip && unzip -o stagehand-automation.zip && rm stagehand-automation.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/9498.zip -OutFile "$d\stagehand-automation.zip"; Expand-Archive "$d\stagehand-automation.zip" -DestinationPath $d -Force; ri "$d\stagehand-automation.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
stagehand-automation.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
stagehand-automationフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Stagehand Automation
概要
Stagehand v3 は、脆弱な従来の自動化と、インテリジェントで自己修復機能を橋渡しする、最先端の AI ブラウザ自動化フレームワークです。Chrome DevTools Protocol (CDP) 上に構築されており、v2 よりも 44% 高速で、Claude とシームレスに統合できます。
主なイノベーション: DOM が変更された場合、テストが中断する代わりに AI が適応します。
コア API:
act()- 自然言語を使用してアクションを実行しますextract()- ページから構造化されたデータを抽出しますobserve()- 要素とページの状態を識別します
クイックスタート (10 分)
1. Stagehand のインストール
npm install @browserbase/stagehand zod
2. Claude API の設定
# .env に追加
ANTHROPIC_API_KEY=your_api_key_here
3. 最初の自動化の記述
import { Stagehand } from "@browserbase/stagehand";
import { z } from "zod";
async function main() {
const stagehand = new Stagehand({
env: "LOCAL",
modelName: "claude-sonnet-4-20250514",
modelClientOptions: {
apiKey: process.env.ANTHROPIC_API_KEY,
},
});
await stagehand.init();
await stagehand.page.goto("https://news.ycombinator.com");
// AI 搭載のアクション - UI の変更にも対応!
await stagehand.act({ action: "click on the first story link" });
// 構造化されたデータの抽出
const data = await stagehand.extract({
instruction: "extract the story title and author",
schema: z.object({
title: z.string(),
author: z.string(),
}),
});
console.log(data);
await stagehand.close();
}
main();
4. 実行
npx ts-node your-script.ts
コア API
act() - アクションの実行
自然言語を使用してアクションを実行します。
// 要素のクリック
await stagehand.act({ action: "click the login button" });
// フォームへの入力
await stagehand.act({ action: "fill in the email field with 'test@example.com'" });
await stagehand.act({ action: "enter password 'securepass123'" });
// ナビゲーション
await stagehand.act({ action: "scroll down to the pricing section" });
await stagehand.act({ action: "click the 'Sign Up' button in the header" });
// 複雑なアクション
await stagehand.act({
action: "select 'Premium' from the plan dropdown and click Continue"
});
自己修復: ボタンの ID が #login-btn から #auth-signin に変更された場合、Stagehand は自動的に適応します。
extract() - 構造化データの取得
スキーマ検証を使用してデータを抽出します。
import { z } from "zod";
// 簡単な抽出
const title = await stagehand.extract({
instruction: "get the main page title",
schema: z.object({
title: z.string(),
}),
});
// 複雑な抽出
const products = await stagehand.extract({
instruction: "extract all products with name, price, and availability",
schema: z.object({
products: z.array(z.object({
name: z.string(),
price: z.number(),
inStock: z.boolean(),
})),
}),
});
// 特定の領域からの抽出
const cartItems = await stagehand.extract({
instruction: "get items in the shopping cart",
schema: z.object({
items: z.array(z.object({
name: z.string(),
quantity: z.number(),
price: z.number(),
})),
total: z.number(),
}),
});
observe() - ページの状態の分析
ページ要素と状態を理解します。
// 要素の検索
const elements = await stagehand.observe({
instruction: "find all clickable buttons on this page"
});
// 状態の確認
const loginState = await stagehand.observe({
instruction: "is the user logged in? Look for profile icons or logout buttons"
});
// フォームフィールドの識別
const formFields = await stagehand.observe({
instruction: "identify all form input fields and their labels"
});
自己修復パターン
従来型 vs Stagehand
// 従来型 (Playwright) - DOM が変更されると中断
await page.click('#submit-btn-v2'); // ID が変更されると失敗
await page.click('.btn-primary:nth-child(2)'); // 順序が変更されると失敗
// STAGEHAND - 自己修復
await stagehand.act({ action: "click the submit button" }); // 常に動作
await stagehand.act({ action: "click the primary action button" }); // 適応
自己修復がアクティブになる場合
- ID/クラスの変更: ボタンの ID が
#old-idから#new-idに変更される - 構造の変更: 要素が DOM ツリー内で移動する
- テキストの変更: ボタンのテキストが "Submit" から "Send" に変更される
- スタイルの変更: CSS クラスが再編成される
キャッシュ (パフォーマンスの最適化)
Stagehand v3 は、検出された要素をキャッシュします。
// 最初の呼び出し: AI がページを分析し、要素を検索 (低速)
await stagehand.act({ action: "click login" });
// 2 回目の呼び出し: キャッシュされたセレクターを使用 (高速)
await stagehand.act({ action: "click login" });
// ページが大幅に変更されるとキャッシュが無効になる
ハイブリッドアプローチ: Playwright + Stagehand
従来の速度と AI の回復力を組み合わせます。
import { Stagehand } from "@browserbase/stagehand";
import { test, expect } from "@playwright/test";
test('hybrid test', async () => {
const stagehand = new Stagehand({ env: "LOCAL" });
await stagehand.init();
// 安定した高速な操作には Playwright を使用
await stagehand.page.goto('https://app.example.com');
await stagehand.page.fill('[data-testid="email"]', 'test@example.com');
// 動的/脆弱な要素には Stagehand を使用
await stagehand.act({ action: "click the login button" });
// アサーションには Playwright を使用
await expect(stagehand.page).toHaveURL(/dashboard/);
// 複雑な抽出には Stagehand を使用
const dashboardData = await stagehand.extract({
instruction: "get user stats from dashboard",
schema: z.object({
totalOrders: z.number(),
accountBalance: z.number(),
}),
});
expect(dashboardData.totalOrders).toBeGreaterThan(0);
});
Claude 統合
モデルの選択
// Claude Sonnet 4 (推奨 - 速度と品質のバランス)
const stagehand = new Stagehand({
modelName: "claude-sonnet-4-20250514",
mod 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Stagehand Automation
Overview
Stagehand v3 is the state-of-the-art AI browser automation framework that bridges brittle traditional automation with intelligent, self-healing capabilities. Built on Chrome DevTools Protocol (CDP), it's 44% faster than v2 and integrates seamlessly with Claude.
Key Innovation: When DOM changes, AI adapts instead of tests breaking.
Core APIs:
act()- Perform actions using natural languageextract()- Extract structured data from pagesobserve()- Identify elements and page state
Quick Start (10 Minutes)
1. Install Stagehand
npm install @browserbase/stagehand zod
2. Configure Claude API
# Add to .env
ANTHROPIC_API_KEY=your_api_key_here
3. Write First Automation
import { Stagehand } from "@browserbase/stagehand";
import { z } from "zod";
async function main() {
const stagehand = new Stagehand({
env: "LOCAL",
modelName: "claude-sonnet-4-20250514",
modelClientOptions: {
apiKey: process.env.ANTHROPIC_API_KEY,
},
});
await stagehand.init();
await stagehand.page.goto("https://news.ycombinator.com");
// AI-powered action - survives UI changes!
await stagehand.act({ action: "click on the first story link" });
// Extract structured data
const data = await stagehand.extract({
instruction: "extract the story title and author",
schema: z.object({
title: z.string(),
author: z.string(),
}),
});
console.log(data);
await stagehand.close();
}
main();
4. Run
npx ts-node your-script.ts
Core APIs
act() - Perform Actions
Execute actions using natural language:
// Click elements
await stagehand.act({ action: "click the login button" });
// Fill forms
await stagehand.act({ action: "fill in the email field with 'test@example.com'" });
await stagehand.act({ action: "enter password 'securepass123'" });
// Navigate
await stagehand.act({ action: "scroll down to the pricing section" });
await stagehand.act({ action: "click the 'Sign Up' button in the header" });
// Complex actions
await stagehand.act({
action: "select 'Premium' from the plan dropdown and click Continue"
});
Self-Healing: If the button ID changes from #login-btn to #auth-signin, Stagehand adapts automatically.
extract() - Get Structured Data
Extract data with schema validation:
import { z } from "zod";
// Simple extraction
const title = await stagehand.extract({
instruction: "get the main page title",
schema: z.object({
title: z.string(),
}),
});
// Complex extraction
const products = await stagehand.extract({
instruction: "extract all products with name, price, and availability",
schema: z.object({
products: z.array(z.object({
name: z.string(),
price: z.number(),
inStock: z.boolean(),
})),
}),
});
// Extract from specific area
const cartItems = await stagehand.extract({
instruction: "get items in the shopping cart",
schema: z.object({
items: z.array(z.object({
name: z.string(),
quantity: z.number(),
price: z.number(),
})),
total: z.number(),
}),
});
observe() - Analyze Page State
Understand page elements and state:
// Find elements
const elements = await stagehand.observe({
instruction: "find all clickable buttons on this page"
});
// Check state
const loginState = await stagehand.observe({
instruction: "is the user logged in? Look for profile icons or logout buttons"
});
// Identify form fields
const formFields = await stagehand.observe({
instruction: "identify all form input fields and their labels"
});
Self-Healing Patterns
Traditional vs Stagehand
// TRADITIONAL (Playwright) - Breaks when DOM changes
await page.click('#submit-btn-v2'); // Fails if ID changes
await page.click('.btn-primary:nth-child(2)'); // Fails if order changes
// STAGEHAND - Self-healing
await stagehand.act({ action: "click the submit button" }); // Always works
await stagehand.act({ action: "click the primary action button" }); // Adapts
When Self-Healing Activates
- ID/Class Changes: Button ID changes from
#old-idto#new-id - Structure Changes: Element moves in DOM tree
- Text Changes: Button text changes from "Submit" to "Send"
- Style Changes: CSS classes reorganized
Caching (Performance Optimization)
Stagehand v3 caches discovered elements:
// First call: AI analyzes page, finds element (slow)
await stagehand.act({ action: "click login" });
// Second call: Uses cached selector (fast)
await stagehand.act({ action: "click login" });
// Cache invalidated when page changes significantly
Hybrid Approach: Playwright + Stagehand
Combine traditional speed with AI resilience:
import { Stagehand } from "@browserbase/stagehand";
import { test, expect } from "@playwright/test";
test('hybrid test', async () => {
const stagehand = new Stagehand({ env: "LOCAL" });
await stagehand.init();
// Use Playwright for stable, fast operations
await stagehand.page.goto('https://app.example.com');
await stagehand.page.fill('[data-testid="email"]', 'test@example.com');
// Use Stagehand for dynamic/fragile elements
await stagehand.act({ action: "click the login button" });
// Use Playwright for assertions
await expect(stagehand.page).toHaveURL(/dashboard/);
// Use Stagehand for complex extraction
const dashboardData = await stagehand.extract({
instruction: "get user stats from dashboard",
schema: z.object({
totalOrders: z.number(),
accountBalance: z.number(),
}),
});
expect(dashboardData.totalOrders).toBeGreaterThan(0);
});
Claude Integration
Model Selection
// Claude Sonnet 4 (recommended - balance of speed/quality)
const stagehand = new Stagehand({
modelName: "claude-sonnet-4-20250514",
modelClientOptions: {
apiKey: process.env.ANTHROPIC_API_KEY,
},
});
// Claude Opus (highest quality, slower)
const stagehand = new Stagehand({
modelName: "claude-opus-4-20250514",
});
// Claude Haiku (fastest, simpler tasks)
const stagehand = new Stagehand({
modelName: "claude-3-5-haiku-20241022",
});
Cost Optimization
// Use Haiku for simple actions (cheaper)
const simpleStagehand = new Stagehand({
modelName: "claude-3-5-haiku-20241022",
});
await simpleStagehand.act({ action: "click login" });
// Use Sonnet for complex extraction
const complexStagehand = new Stagehand({
modelName: "claude-sonnet-4-20250514",
});
const data = await complexStagehand.extract({
instruction: "extract all product details with nested specifications",
schema: complexSchema,
});
Estimated Costs
| Operation | Model | Est. Cost |
|---|---|---|
| Simple act() | Haiku | ~$0.001 |
| Complex act() | Sonnet | ~$0.005 |
| Simple extract() | Haiku | ~$0.002 |
| Complex extract() | Sonnet | ~$0.01 |
MCP Integration
Use Stagehand with Claude Desktop via Model Context Protocol:
// Stagehand MCP server enables Claude to control browsers
// from Claude Desktop or any MCP-compatible client
import { StagehandMCPServer } from "@browserbase/stagehand/mcp";
const server = new StagehandMCPServer();
server.start();
// Now Claude can call:
// - stagehand.act({ action: "..." })
// - stagehand.extract({ instruction: "..." })
// - stagehand.observe({ instruction: "..." })
Error Handling
try {
await stagehand.act({
action: "click the non-existent button",
timeout: 10000, // 10 second timeout
});
} catch (error) {
if (error.message.includes('timeout')) {
console.log('Element not found within timeout');
} else if (error.message.includes('multiple')) {
console.log('Multiple matching elements found - be more specific');
} else {
throw error;
}
}
// Retry pattern
async function actWithRetry(stagehand, action, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await stagehand.act({ action });
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(r => setTimeout(r, 1000));
}
}
}
Best Practices
1. Be Specific in Instructions
// BAD - ambiguous
await stagehand.act({ action: "click button" });
// GOOD - specific
await stagehand.act({ action: "click the blue 'Add to Cart' button below the product image" });
2. Use Context
// Provide context for better accuracy
await stagehand.act({
action: "in the navigation menu, click on 'Settings'"
});
await stagehand.act({
action: "in the user dropdown in the top right, click 'Logout'"
});
3. Combine with Playwright for Speed
// Fast: Use Playwright for data-testid elements
await stagehand.page.click('[data-testid="submit"]');
// Resilient: Use Stagehand for dynamic elements
await stagehand.act({ action: "dismiss the cookie banner" });
4. Schema Validation
// Always use Zod schemas for type safety
const schema = z.object({
title: z.string().min(1),
price: z.number().positive(),
inStock: z.boolean(),
});
const data = await stagehand.extract({
instruction: "get product details",
schema,
});
// data is fully typed!
Use Cases
- Self-Healing E2E Tests: Tests that survive UI redesigns
- Web Scraping: Extract data from any website
- Form Automation: Fill complex forms automatically
- Testing AI Chatbots: Interact with conversational UIs
- Cross-Site Workflows: Automate multi-site processes
References
references/stagehand-v3-guide.md- Complete API referencereferences/claude-integration.md- API setup and model selectionreferences/self-healing-patterns.md- Advanced patterns
Stagehand v3 brings AI-powered self-healing to browser automation - tests that adapt instead of break.