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",
});
import os
from stagehand import Stagehand
# Basic usage
# Defaults to Browserbase; if no API key is provided, it will default to LOCAL
# Default model is gpt-4.1-mini
stagehand = Stagehand()
# Custom configuration
def custom_logger(log_line):
print(f"[{log_line.category}] {log_line.message}")
stagehand = Stagehand(
env="LOCAL",
# env="BROWSERBASE", # To run remotely on Browserbase (needs API keys)
verbose=1,
enable_caching=True,
logger=custom_logger,
# LLM configuration
model_name="google/gemini-2.0-flash", # Name of the model to use in "provider/model" format
model_api_key=os.getenv("GOOGLE_GENERATIVE_AI_API_KEY"), # Model API key
api_key=os.getenv("BROWSERBASE_API_KEY"),
project_id=os.getenv("BROWSERBASE_PROJECT_ID"),
# API keys for authentication (if you want to use Browserbase)
browserbase_session_id=None, # Can set Session ID for resuming Browserbase sessions
browserbase_session_create_params={ # Browser Session Params
"project_id": os.getenv("BROWSERBASE_PROJECT_ID"),
"proxies": True, # Using Browserbase's Proxies
"browser_settings": {
"advanced_stealth": True, # Only available on Scale Plans
"block_ads": True, # To Block Ad Popups (defaults to False)
"viewport": { # Browser Size (ie 1920x1080, 1024x768)
"width": 1024,
"height": 768,
},
},
},
local_browser_launch_options={
"headless": True, # Launches the browser in headless mode.
"executable_path": "/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.
"handle_sighup": True,
"handle_sigint": True,
"handle_sigterm": True,
"ignore_default_args": False, # or specify a list of arguments to ignore.
"proxy": {
"server": "http://proxy.example.com:8080",
"bypass": "localhost",
"username": "user",
"password": "pass"
},
"traces_dir": "/path/to/traces", # Directory to store trace files.
"user_data_dir": "/path/to/user/data", # Custom user data directory.
"accept_downloads": True,
"downloads_path": "/path/to/downloads",
"extra_http_headers": {"User-Agent": "Custom Agent"},
"geolocation": {"latitude": 37.7749, "longitude": -122.4194, "accuracy": 10},
"permissions": ["geolocation", "notifications"],
"locale": "en-US",
"viewport": {"width": 1280, "height": 720},
"device_scale_factor": 1,
"has_touch": False,
"ignore_https_errors": True,
"record_video": {"dir": "/path/to/videos", "size": {"width": 1280, "height": 720}},
"record_har": {
"path": "/path/to/har.har",
"mode": "full",
"omit_content": False,
"content": "embed",
"url_filter": ".*"
},
"chromium_sandbox": True,
"devtools": True,
"bypass_csp": False,
"cdp_url": "http://localhost:9222",
},
)
# Resume existing Browserbase session
stagehand = Stagehand(
env="BROWSERBASE",
browserbase_session_id="existing-session-id",
)
参数: ConstructorParams
- TypeScript
- Python
'LOCAL' | 'BROWSERBASE'
默认为
'BROWSERBASE'string
您的 Browserbase API 密钥。默认为环境变量
BROWSERBASE_API_KEYstring
您的 Browserbase 项目 ID。默认为环境变量
BROWSERBASE_PROJECT_IDboolean
启用实验性功能访问
boolean
是否使用 stagehand API。当
env: "BROWSERBASE" 时默认为 trueobject
创建新 Browserbase 会话的配置选项。更多关于 browserbaseSessionCreateParams 的信息请参见此处
显示 属性
显示 属性
object
显示 属性
显示 属性
object
使用示例参见隐身模式页面
boolean
启用或禁用浏览器广告拦截。默认为
falseboolean
启用或禁用浏览器验证码解决。默认为
trueboolean
启用或禁用会话录制。默认为
trueboolean
高级浏览器隐身模式
boolean
设置为 true 可在断开连接后保持会话活动。仅适用于 Browserbase Startup 计划
boolean
代理配置。可为 true 使用默认代理,或代理配置数组
enum<string>
会话运行区域。可用选项:
us-west-2, us-east-1, eu-central-1, ap-southeast-1number
会话自动结束前的持续时间(秒)。默认为项目的 defaultTimeout
有效范围:
60 < x < 21600string
要恢复的现有 Browserbase 会话 ID
object
语言模型客户端的配置选项(如
apiKey)boolean
启用 LLM 响应缓存。设置为
true 时,LLM 请求将被缓存到磁盘并重复用于相同请求。默认为 falseinteger
指定等待 DOM 稳定的超时时间(毫秒)。默认为
30_000 (30 秒)boolean
是否禁用 Pino 日志记录。适用于 Next.js 或测试环境。如果定义了自定义
logger,Pino 将自动禁用integer
在自动化过程中启用多级日志记录:
0: ERROR (极少或不记录)1: INFO (SDK 级别日志)2: DEBUG (详细日志和跟踪)
string
用于 LLM 的自定义系统提示,附加到 act、extract 和 observe 方法的默认系统提示
boolean
启用自愈模式。设置为
true 时,Stagehand 将尝试从错误中恢复(例如过期的缓存元素无法解析)。默认为 true。设置为 false 可禁用缓存错误时的 LLM 推断LocalBrowserLaunchOptions
提供本地浏览器实例的全面选项
显示 属性
显示 属性
string[]
传递给浏览器的额外命令行参数
boolean
启用或禁用 Chromium 沙箱
boolean
启动时打开浏览器的开发者工具
Record<string, string | number | boolean>
浏览器进程的环境变量
string
浏览器可执行文件路径
boolean
处理 SIGHUP 信号的选项
boolean
处理 SIGINT 信号的选项
boolean
处理 SIGTERM 信号的选项
boolean
以无头模式启动浏览器
boolean | string[]
忽略所有默认参数或指定要忽略的数组
string
存储跟踪文件的目录
string
自定义用户数据目录
boolean
允许文件下载
string
下载文件保存目录
Record<string, string>
随每个请求发送的额外 HTTP 头
boolean
指示设备是否具有触摸功能
boolean
是否忽略 HTTPS 错误
string
设置浏览器的语言环境
string[]
授予的权限数组(如”geolocation”, “notifications”)
object
number
高 DPI 显示器的设备缩放因子
string
模拟的时区(如”America/Los_Angeles”)
boolean
是否绕过内容安全策略
Cookie[]
初始化浏览器会话的 cookie 数组
string
用于 Chrome DevTools 协议的 URL。适用于连接到正在运行的浏览器实例
boolean
是否在 Stagehand 关闭后保留用户数据目录。适用于在多个会话中重用本地上下文。默认为 false
'LOCAL' | 'BROWSERBASE'
默认为
'BROWSERBASE'string
您的 Browserbase API 密钥。默认为环境变量
BROWSERBASE_API_KEYstring
您的 Browserbase 项目 ID。默认为环境变量
BROWSERBASE_PROJECT_IDboolean
启用实验性功能访问
boolean
是否使用 stagehand API。当
env: "BROWSERBASE" 时默认为 trueobject
创建新 Browserbase 会话的配置选项。更多关于 browserbaseSessionCreateParams 的信息请参见此处
显示 属性
显示 属性
object
显示 属性
显示 属性
object
使用示例参见隐身模式页面
boolean
启用或禁用浏览器广告拦截。默认为
falseboolean
启用或禁用浏览器验证码解决。默认为
trueboolean
启用或禁用会话录制。默认为
trueboolean
高级浏览器隐身模式
boolean
设置为 true 可在断开连接后保持会话活动。仅适用于 Browserbase Startup 计划
boolean
代理配置。可为 true 使用默认代理,或代理配置数组
enum<string>
会话运行区域。可用选项:
us-west-2, us-east-1, eu-central-1, ap-southeast-1number
会话自动结束前的持续时间(秒)。默认为项目的 defaultTimeout
有效范围:
60 < x < 21600string
要恢复的现有 Browserbase 会话 ID
object
语言模型客户端的配置选项(如
apiKey)integer
指定等待 DOM 稳定的超时时间(毫秒)。默认为
30_000 (30 秒)integer
在自动化过程中启用多级日志记录:
0: ERROR (极少或不记录)1: INFO (SDK 级别日志)2: DEBUG (详细日志和跟踪)
string
用于 LLM 的自定义系统提示,附加到 act、extract 和 observe 方法的默认系统提示
boolean
启用自愈模式。设置为
true 时,Stagehand 将尝试从错误中恢复(例如过期的缓存元素无法解析)。默认为 true。设置为 false 可禁用缓存错误时的 LLM 推断integer
指定 act 命令的超时时间(毫秒)。默认为
30_000 (30 秒)boolean
以无头模式启动浏览器
boolean
是否使用 Rich 进行彩色日志记录。默认为
trueLocalBrowserLaunchOptions
提供本地浏览器实例的全面选项
显示 属性
显示 属性
string[]
传递给浏览器的额外命令行参数
boolean
启用或禁用 Chromium 沙箱
boolean
启动时打开浏览器的开发者工具
Record<string, string | number | boolean>
浏览器进程的环境变量
string
浏览器可执行文件路径
boolean
处理 SIGHUP 信号的选项
boolean
处理 SIGINT 信号的选项
boolean
处理 SIGTERM 信号的选项
boolean
以无头模式启动浏览器
boolean | string[]
忽略所有默认参数或指定要忽略的数组
string
存储跟踪文件的目录
string
自定义用户数据目录
boolean
允许文件下载
string
下载文件保存目录
Record<string, string>
随每个请求发送的额外 HTTP 头
boolean
指示设备是否具有触摸功能
boolean
是否忽略 HTTPS 错误
string
设置浏览器的语言环境
string[]
授予的权限数组(如”geolocation”, “notifications”)
object
number
高 DPI 显示器的设备缩放因子
string
模拟的时区(如”America/Los_Angeles”)
boolean
是否绕过内容安全策略
Cookie[]
初始化浏览器会话的 cookie 数组
string
用于 Chrome DevTools 协议的 URL。适用于连接到正在运行的浏览器实例
boolean
是否在 Stagehand 关闭后保留用户数据目录。适用于在多个会话中重用本地上下文。默认为 false
返回值: Stagehand 对象
构造函数返回一个配置了指定选项的Stagehand 类实例。但使用 Stagehand 前,仍需通过 init() 方法进行初始化。
stagehand.init()
await stagehand.init();
await stagehand.init()
init() 方法异步初始化 Stagehand 实例。该方法应在调用其他任何方法前执行。
stagehand.close()
await stagehand.close();
await stagehand.close()
close() 是清理方法,用于移除 Stagehand 创建的临时文件。建议在自动化任务完成后显式调用该方法。
