跳转到主要内容

Stagehand 构造函数

// Basic usage
// Defaults to Browserbase; if no API key is provided, it will default to LOCAL
// Default model is gpt-4o
const stagehand = new Stagehand();

// Custom configuration
const stagehand = new Stagehand({
	env: "LOCAL",
	// env: "BROWSERBASE", // To run remotely on Browserbase (needs API keys)
	verbose: 1,
	enableCaching: true,
	logger: (logLine: LogLine) => {
		console.log(`[${logLine.category}] ${logLine.message}`);
	},
    // LLM configuration
    modelName: "google/gemini-2.0-flash", /* Name of the model to use in "provider/model" format */
    modelClientOptions: {
      apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY, /* Model API key */
    }, /* Configuration options for the model client */
	apiKey: process.env.BROWSERBASE_API_KEY, 
	projectId: process.env.BROWSERBASE_PROJECT_ID,
	/* API keys for authentication (if you want to use Browserbase) */
	browserbaseSessionID:
      undefined, /* Can set Session ID for resuming Browserbase sessions */
    browserbaseSessionCreateParams: { /* Browser Session Params */
      projectId: process.env.BROWSERBASE_PROJECT_ID!,
      proxies: true, /* Using Browserbase's Proxies */ 
      browserSettings: {
		advancedStealth: true, /* Only available on Scale Plans */
        blockAds: true, /* To Block Ad Popups (defaults to False) */
        viewport: { // Browser Size (ie 1920x1080, 1024x768)
          width: 1024,
          height: 768,
        },
      },
    },
    localBrowserLaunchOptions: {
        headless: true, // Launches the browser in headless mode.
        executablePath: '/path/to/chrome', // Custom path to the Chrome executable.
        args: ['--no-sandbox', '--disable-setuid-sandbox'], // Additional launch arguments.
        env: { NODE_ENV: "production" }, // Environment variables for the browser process.
        handleSIGHUP: true,
        handleSIGINT: true,
        handleSIGTERM: true,
        ignoreDefaultArgs: false, // or specify an array of arguments to ignore.
        proxy: {
            server: 'http://proxy.example.com:8080',
            bypass: 'localhost',
            username: 'user',
            password: 'pass'
        },
        tracesDir: '/path/to/traces', // Directory to store trace files.
        userDataDir: '/path/to/user/data', // Custom user data directory.
        acceptDownloads: true,
        downloadsPath: '/path/to/downloads',
        extraHTTPHeaders: { 'User-Agent': 'Custom Agent' },
        geolocation: { latitude: 37.7749, longitude: -122.4194, accuracy: 10 },
        permissions: ["geolocation", "notifications"],
        locale: "en-US",
        viewport: { width: 1280, height: 720 },
        deviceScaleFactor: 1,
        hasTouch: false,
        ignoreHTTPSErrors: true,
        recordVideo: { dir: '/path/to/videos', size: { width: 1280, height: 720 } },
        recordHar: {
            path: '/path/to/har.har',
            mode: "full",
            omitContent: false,
            content: "embed",
            urlFilter: '.*'
        },
        chromiumSandbox: true,
        devtools: true,
        bypassCSP: false,
		cdpUrl: 'http://localhost:9222',
        preserveUserDataDir: false, // Whether to preserve the user data directory after Stagehand is closed. Defaults to false.
    },
});

// Resume existing Browserbase session
const stagehand = new Stagehand({
	env: "BROWSERBASE",
	browserbaseSessionID: "existing-session-id",
});
该构造函数用于创建 Stagehand 实例。

参数: ConstructorParams

env
'LOCAL' | 'BROWSERBASE'
默认为 'BROWSERBASE'
apiKey
string
您的 Browserbase API 密钥。默认为环境变量 BROWSERBASE_API_KEY
projectId
string
您的 Browserbase 项目 ID。默认为环境变量 BROWSERBASE_PROJECT_ID
experimental
boolean
启用实验性功能访问
useAPI
boolean
是否使用 stagehand API。当 env: "BROWSERBASE" 时默认为 true
browserbaseSessionCreateParams
object
创建新 Browserbase 会话的配置选项。更多关于 browserbaseSessionCreateParams 的信息请参见此处
browserbaseSessionID
string
要恢复的现有 Browserbase 会话 ID
modelName
string
指定使用的默认语言模型。支持格式为 {provider}/{modelName}。支持的提供商列表参见可用提供商
modelClientOptions
object
语言模型客户端的配置选项(如 apiKey)
enableCaching
boolean
启用 LLM 响应缓存。设置为 true 时,LLM 请求将被缓存到磁盘并重复用于相同请求。默认为 false
domSettleTimeoutMs
integer
指定等待 DOM 稳定的超时时间(毫秒)。默认为 30_000 (30 秒)
logger
(message: LogLine) => void
messageLogLine 对象。处理日志消息。用于自定义日志实现。更多信息参见日志页面
disablePino
boolean
是否禁用 Pino 日志记录。适用于 Next.js 或测试环境。如果定义了自定义 logger,Pino 将自动禁用
verbose
integer
在自动化过程中启用多级日志记录:
  • 0: ERROR (极少或不记录)
  • 1: INFO (SDK 级别日志)
  • 2: DEBUG (详细日志和跟踪)
llmClient
LLMClient
符合 LLMClient 抽象类的自定义 LLM 客户端实现
systemPrompt
string
用于 LLM 的自定义系统提示,附加到 act、extract 和 observe 方法的默认系统提示
selfHeal
boolean
启用自愈模式。设置为 true 时,Stagehand 将尝试从错误中恢复(例如过期的缓存元素无法解析)。默认为 true。设置为 false 可禁用缓存错误时的 LLM 推断
localBrowserLaunchOptions
LocalBrowserLaunchOptions
提供本地浏览器实例的全面选项

返回值: Stagehand 对象

构造函数返回一个配置了指定选项的 Stagehand 类实例。但使用 Stagehand 前,仍需通过 init() 方法进行初始化。

stagehand.init()

await stagehand.init();
init() 方法异步初始化 Stagehand 实例。该方法应在调用其他任何方法前执行。

stagehand.close()

await stagehand.close();
close() 是清理方法,用于移除 Stagehand 创建的临时文件。建议在自动化任务完成后显式调用该方法。