stagehand README

项目的 README,来自 github.com/browserbase/stagehand。合并为一个 markdown 文件:README.md。

Stagehand is the SDK for browser agents

browserbase%2Fstagehand | Trendshift

Docs · Quickstart · ⭐ Star this repo

MIT License Discord Community Ask DeepWiki

Stagehand homepage showing browser automation in TypeScript, Python, and Go and a speed comparison with Playwright

AI that uses the browser like humans.

Sign in once, keep the session, and pull structured data out the other side.

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod/v4";

// Cookies persist in ./browser-data, so the next run starts already signed in
const browser = await localBrowser.launch({ userDataDir: "./browser-data" });
const stagehand = await Stagehand.create({
  browser,
  model: { modelName: "openai/gpt-5.4-mini", apiKey: process.env.OPENAI_API_KEY },
});

const [page] = await browser.context.pages();
await page.goto("https://app.example.com/login");

// observe() returns real selectors, so credentials never reach the model
const { data: email } = await stagehand.observe("find the email input");
const { data: password } = await stagehand.observe("find the password input");
await page.locator(email[0].selector).fill(process.env.APP_EMAIL!);
await page.locator(password[0].selector).fill(process.env.APP_PASSWORD!);

// act() self-heals when the site redesigns its form
await stagehand.act("click the sign in button");
await stagehand.act("open the billing page");

// extract() returns schema-validated data
const { data } = await stagehand.extract(
  "extract every invoice in the table",
  z.object({
    invoices: z.array(z.object({ number: z.string(), amount: z.number(), paid: z.boolean() })),
  }),
);

console.log(data.invoices);

await stagehand.close();
await browser.close();
Python
import asyncio
import os

from pydantic import BaseModel
from stagehand import Stagehand, local_browser


class Invoice(BaseModel):
    number: str
    amount: float
    paid: bool


class Invoices(BaseModel):
    invoices: list[Invoice]


async def main() -> None:
    # Cookies persist in ./browser-data, so the next run starts already signed in
    browser = await local_browser.launch(user_data_dir="./browser-data")
    try:
        stagehand = await Stagehand.create(
            browser=browser,
            model="openai/gpt-5.4-mini",
            model_api_key=os.environ["OPENAI_API_KEY"],
        )
        try:
            page = (await browser.context.pages())[0]
            await page.goto("https://app.example.com/login")

            # observe() returns real selectors, so credentials never reach the model
            email = await stagehand.observe("find the email input")
            password = await stagehand.observe("find the password input")
            await page.locator(email.data[0].selector).fill(os.environ["APP_EMAIL"])
            await page.locator(password.data[0].selector).fill(os.environ["APP_PASSWORD"])

            # act() self-heals when the site redesigns its form
            await stagehand.act("click the sign in button")
            await stagehand.act("open the billing page")

            # extract() returns schema-validated data
            result = await stagehand.extract(
                "extract every invoice in the table",
                Invoices,
            )
            print(result.data.invoices)
        finally:
            await stagehand.close()
    finally:
        await browser.close()


asyncio.run(main())
Go
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	stagehand "github.com/browserbase/stagehand/packages/sdk-go/v4"
)

type invoice struct {
	Number string  `json:"number"`
	Amount float64 `json:"amount"`
	Paid   bool    `json:"paid"`
}

type invoices struct {
	Invoices []invoice `json:"invoices"`
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) (err error) {
	// Cookies persist in ./browser-data, so the next run starts already signed in
	browser, err := stagehand.LaunchLocalBrowser(ctx, &stagehand.LocalBrowserLaunchOptions{
		UserDataDir: "./browser-data",
	})
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, browser.Close(ctx)) }()

	modelAPIKey := os.Getenv("OPENAI_API_KEY")
	client, err := stagehand.Create(ctx, stagehand.CreateOptions{
		Browser: browser,
		Model: &stagehand.ModelConfig{
			ModelName: "openai/gpt-5.4-mini",
			APIKey:    &modelAPIKey,
		},
	})
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, client.Close(ctx)) }()

	browserContext, err := browser.Context()
	if err != nil {
		return err
	}
	pages, err := browserContext.Pages(ctx)
	if err != nil {
		return err
	}
	page := pages[0]
	if _, err := page.Goto(ctx, "https://app.example.com/login", nil); err != nil {
		return err
	}

	// Observe returns real selectors, so credentials never reach the model
	emailInstruction := "find the email input"
	email, err := client.Observe(ctx, &emailInstruction, nil)
	if err != nil {
		return err
	}
	if err := page.Locator(email.Data[0].Selector).Fill(ctx, os.Getenv("APP_EMAIL")); err != nil {
		return err
	}

	passwordInstruction := "find the password input"
	password, err := client.Observe(ctx, &passwordInstruction, nil)
	if err != nil {
		return err
	}
	if err := page.Locator(password.Data[0].Selector).Fill(ctx, os.Getenv("APP_PASSWORD")); err != nil {
		return err
	}

	// Act self-heals when the site redesigns its form
	if _, err := client.Act(ctx, stagehand.ActInstruction("click the sign in button"), nil); err != nil {
		return err
	}
	if _, err := client.Act(ctx, stagehand.ActInstruction("open the billing page"), nil); err != nil {
		return err
	}

	// Extract returns data decoded into a Go type
	extracted, err := stagehand.Extract[invoices](
		ctx,
		client,
		"extract every invoice in the table",
		nil,
	)
	if err != nil {
		return err
	}
	fmt.Println(extracted.Data.Invoices)

	return nil
}

Install

pnpm add @browserbasehq/stagehand 'zod@~4.4.3'
Python
pip install stagehand
Go
go get github.com/browserbase/stagehand/packages/sdk-go/[email protected]

Local runs need Chrome installed. Full setup: Quickstart.

Using a coding agent? (Claude Code, Cursor, Codex)

Install the browse CLI and skill instead of using the SDK directly:

npm install -g browse
npx skills add browserbase/stagehand --skill browse
browse open https://example.com --local
browse snapshot
browse get title

No LLM key or Browserbase account needed for local use. See CLI vs SDK vs hosted MCP for when to use each.

Why Stagehand

Familiar APIs The Playwright-style methods you and your agents already know: goto, click, locator, screenshot.
Token efficiency Hybrid accessibility-tree trimming gives agents exactly the page context they need and nothing more.
Faster in production Stagehand runs as an extension next to the browser, cutting round-trip latency on every action.
Self-healing act, observe, and extract refresh how an action happens when the site changes underneath it.
Built for agents WebMCP, clipboard support, batch commands, deep locators for nested iframes and closed Shadow DOMs, OTel traces.
Three languages One complete browser driver across TypeScript, Python, and Go.

Run it on Browserbase

Point the same script at Browserbase and get 2x faster execution than Playwright cloud equivalent browsers. Configure the Model Gateway so you never wire up a provider, and enable server-side caching to cache repeated actions.

import { browserbase, Stagehand } from "@browserbasehq/stagehand";

const browser = await browserbase.launch({ apiKey: process.env.BROWSERBASE_API_KEY! });

// No model configuration: the Model Gateway picks the cheapest model for each action
// cache: true: identical calls come back from Browserbase, no tokens spent
const stagehand = await Stagehand.create({ browser, cache: true });
Python
import os

from stagehand import Stagehand, browserbase

browser = await browserbase.launch(api_key=os.environ["BROWSERBASE_API_KEY"])

# No model configuration: the Model Gateway picks the cheapest model for each action
# cache=True: identical calls come back from Browserbase, no tokens spent
stagehand = await Stagehand.create(browser=browser, cache=True)
Go
browser, err := stagehand.LaunchBrowserbase(ctx, stagehand.BrowserbaseLaunchOptions{
	APIKey: os.Getenv("BROWSERBASE_API_KEY"),
})
if err != nil {
	return err
}

// No model configuration: the Model Gateway picks the cheapest model for each action
// CacheEnabled(true): identical calls come back from Browserbase, no tokens spent
cache := stagehand.CacheEnabled(true)
client, err := stagehand.Create(ctx, stagehand.CreateOptions{
	Browser: browser,
	Cache:   &cache,
})
if err != nil {
	return err
}

Verified mode, residential proxies, persistent contexts, and session recordings come with it. Get an API key and learn how to configure your browser here.

Hosted MCP: browser tools without installing anything

The hosted Browserbase MCP server puts navigate, act, observe, and extract in any MCP client — no install, no local browser. Requires a Browserbase API key.

claude mcp add --transport http browserbase https://mcp.browserbase.com/mcp \
  --header "Authorization: Bearer $BROWSERBASE_API_KEY"
Cursor, Codex, and other MCP clients
{
  "mcpServers": {
    "browserbase": {
      "url": "https://mcp.browserbase.com/mcp",
      "headers": { "Authorization": "Bearer YOUR_BROWSERBASE_API_KEY" }
    }
  }
}

For local browsing without an API key, use the browse CLI instead.

Search and fetch without a browser

Fetch lets you grab the content of any URL as markdown. Search provides fast, token-efficient web search results. Both as a lightweight complement to browser sessions.

import { browserbase } from "@browserbasehq/stagehand";

const { results } = await browserbase.search({
  apiKey: process.env.BROWSERBASE_API_KEY!,
  query: "browser agent frameworks",
  numResults: 5,
});

const fetched = await browserbase.fetch({
  apiKey: process.env.BROWSERBASE_API_KEY!,
  url: results[0].url,
  format: "markdown",
});

console.log(fetched.content);

Docs and resources

Quickstart Empty directory to working automation in three steps
page · locator Playwright-style browser and element APIs
WebMCP Discover and invoke WebMCP tools exposed by web pages
act · extract · observe Browser actions and data extraction with natural language
Search · Fetch Web search and page content without a browser
Migrate from Playwright Port an existing suite
Integrations Mastra, Deep Agents, Vercel AI SDK, Claude Code, Codex
Python SDK · Go SDK Language-specific guides
Ask DeepWiki Ask questions about this codebase

Join the community

Stagehand is built in the open, and the fastest way to shape it is to show up.

Contributing

We're focused on improving reliability, extensibility, speed, and cost, in that order. Bug fixes and small improvements are the best way to get started. For anything larger, reach out to Miguel Gonzalez or Paul Klein on Discord first so we can make sure it lands.

Stagehand is a TypeScript, Python, and Go monorepo driven by just:

git clone https://github.com/browserbase/stagehand.git
cd stagehand
just install
just generate
just build

export OPENAI_API_KEY="your-openai-api-key"
just example act # runs packages/sdk-ts/examples/act.ts

See CONTRIBUTING.md for the full TypeScript, Python, and Go setup.

Acknowledgements

We'd like to thank the following people for their major contributions to Stagehand:

License

Licensed under the MIT License.

Copyright 2026 Browserbase, Inc.

"Stagehand" is a trademark of Browserbase, Inc.

stagehand (browserbase/stagehand)

正在搜索数据库…

这是什么?Stagehand 是一个用于构建浏览器代理的 SDK——也就是驱动真实浏览器去提取数据并与任意网站交互的代码代理或 AI 代理,提供 TypeScript、Python 和 Go 的 SDK。
它和直接用 Playwright 有什么不同?Playwright 是为测试而生的;Stagehand 是为代理而生的。你仍可以使用 Playwright 风格的方法(goto、click、locator、screenshot),同时还能加入自然语言的 act、observe 和 extract 操作、专为代理优化的页面上下文,以及对跨进程 iframe 和封闭 Shadow DOM 的支持。
TypeScript 项目的搭建流程是什么样的?按照 docs.stagehand.dev 上的快速入门指南,安装你所用语言的 SDK(TypeScript 侧需要 Node >= 22.18.0)。导出 LLM 提供商的 API 密钥和 Browserbase 凭据,然后运行 packages/sdktz/examples 里的示例脚本。
网站改版之后,我的自动化会怎样?Stagehand 会检测到变化并自动刷新操作的执行方式,让你的代理自行恢复,而不是悄悄失效。
它是给做网站测试的 QA 工程师用的,还是给构建代理的开发者用的?给构建浏览器代理和生产级网页自动化的开发者用的——Stagehand 把自己定位为 Playwright 测试定位的代理版对应物,把可靠性、可观测性和成本当作生产环境的问题来对待。
Stagehand 到底运行在哪里?它是一个代码 SDK,而不是需要安装的应用:TypeScript SDK 运行在 Node.js 22.18.0 及以上版本,另外还有 Python 和 Go 的 SDK,分别运行在它们各自的常规运行时上。
Stagehand 免费开源吗?是的——它采用 MIT 许可证,由 Browserbase, Inc. 开发。
我的代理会不会为了读取整页内容而浪费 token?token 效率是其明确承诺的优先事项:Stagehand 的混合无障碍树裁剪只给代理恰好需要的页面上下文——不多一分。
每个任务都需要完整的浏览器会话吗?不需要——同一个 browserbase 接口还提供了无需启动浏览器的 Browserbase Search 和 Fetch,简单的查询完全可以跳过页面自动化。
我可以把 Claude Code 或 Codex 这类编程代理接到它上面吗?可以——项目说明中把 Claude Code、Codex、Eve 和 Mastra 列为受支持的上手方式。
它自带哪些生产环境功能?WebMCP 支持、剪贴板支持、批量命令、用于嵌套 iframe 的深度定位器,以及 OpenTelemetry(OTel)支持。团队表示他们的优先级依次是可靠性、可扩展性、速度和成本。
大小
202.4 MB
星标
26.1K
时长
2年
提交 · 90 天