Skip to main content
Version: Next

@crawlee/stagehand

Provides AI-powered web crawling using Stagehand for natural language browser automation. The enhanced page object offers page.act() to perform actions with plain English, page.extract() to get structured data with Zod schemas, and page.observe() to discover available actions.

Since StagehandCrawler uses AI models for page interaction, it is useful for crawling websites with complex or frequently changing layouts where traditional CSS selectors are difficult to maintain. If the target website has a stable structure, consider using PlaywrightCrawler, which is faster and doesn't require AI API keys.

The crawler extends BrowserCrawler and supports all standard Crawlee features including request queues, proxy rotation, autoscaling, and browser fingerprinting.

API Key Configuration

The apiKey option is interpreted based on the env setting:

  • env: 'LOCAL' (default): apiKey is the LLM provider key (OpenAI, Anthropic, or Google)
  • env: 'BROWSERBASE': apiKey is the Browserbase API key
const crawler = new StagehandCrawler({
stagehandOptions: {
model: 'openai/gpt-4.1-mini',
apiKey: 'your-api-key', // LLM API key for LOCAL env
},
// ...
});

Alternatively, you can use environment variables (used as fallback when apiKey is not provided):

  • OpenAI: OPENAI_API_KEY
  • Anthropic: ANTHROPIC_API_KEY
  • Google: GOOGLE_API_KEY

Example usage

import { StagehandCrawler } from '@crawlee/stagehand';
import { z } from 'zod';

const crawler = new StagehandCrawler({
stagehandOptions: {
model: 'openai/gpt-4.1-mini',
},
async requestHandler({ page, request, log }) {
log.info(`Processing ${request.url}`);

// Use natural language to interact with the page
await page.act('Click the "Load More" button');

// Extract structured data with AI
const data = await page.extract(
'Get all product names and prices',
z.object({
products: z.array(z.object({
name: z.string(),
price: z.number(),
})),
}),
);

log.info(`Found ${data.products.length} products`);
},
});

await crawler.run(['https://example.com']);

AI-powered web crawling with Stagehand integration for Crawlee.

This package provides StagehandCrawler, which extends BrowserCrawler with natural language browser automation capabilities powered by Browserbase's Stagehand library.

Key Features

  • Natural Language Actions: Use page.act() to perform actions with plain English instructions
  • Structured Data Extraction: Use page.extract() with Zod schemas for type-safe data extraction
  • Action Discovery: Use page.observe() to get AI-suggested actions
  • Autonomous Agents: Use page.agent() for complex multi-step workflows
  • Anti-Blocking: Automatic browser fingerprinting and Cloudflare bypass
  • Browserbase Integration: Optional cloud browser support
import { StagehandCrawler } from '@crawlee/stagehand';
import { z } from 'zod';

const crawler = new StagehandCrawler({
stagehandOptions: {
env: 'LOCAL',
model: 'openai/gpt-4.1-mini',
},
async requestHandler({ page, request, log }) {
log.info(`Processing ${request.url}`);

// Use natural language to interact
await page.act('Click the Products link');

// Extract structured data
const products = await page.extract(
'Get all products',
z.object({
items: z.array(z.object({
name: z.string(),
price: z.number(),
})),
})
);

await Dataset.pushData(products);
},
});

await crawler.run(['https://example.com']);

Index

Browser management

Other

Other

AddRequestsBatchedOptions

AddRequestsBatchedResult

ApifyLogAdapter

Re-exports ApifyLogAdapter

ArgumentValidationError

assertBrowserPoolNotConfigured

BaseCrawleeLogger

BasicCrawler

Re-exports BasicCrawler

BasicCrawlerOptions

BasicCrawlingContext

BLOCKED_STATUS_CODES

BrowserCrawler

Re-exports BrowserCrawler

BrowserCrawlerOptions

BrowserCrawlingContext

BrowserHook

Re-exports BrowserHook

BrowserLaunchContext

CalculatedStatistics

coerceBoolean

Re-exports coerceBoolean

coerceNumber

Re-exports coerceNumber

ConcurrencyConsumer

ConcurrencySystem

ConcurrencySystemOptions

ConfigField

Re-exports ConfigField

Configuration

Re-exports Configuration

ConfigurationInput

ConfigurationOptions

ContextMiddleware

ContextPipeline

Re-exports ContextPipeline

ContextPipelineCleanupError

ContextPipelineInitializationError

ContextPipelineInterruptedError

CpuLoadSignal

Re-exports CpuLoadSignal

CpuLoadSignalOptions

crawleeConfigFields

CrawleeLogger

Re-exports CrawleeLogger

CrawleeLoggerOptions

CrawlerAddRequestsOptions

CrawlerAddRequestsResult

CrawlerRunOptions

CrawlingContext

Re-exports CrawlingContext

createBasicRouter

CreateContextOptions

CreateSession

Re-exports CreateSession

createStorageTransaction

CriticalError

Re-exports CriticalError

Dataset

Re-exports Dataset

DatasetConsumer

Re-exports DatasetConsumer

DatasetContent

Re-exports DatasetContent

DatasetDataOptions

DatasetExportOptions

DatasetExportToOptions

DatasetIteratorOptions

DatasetJournalEntry

DatasetMapper

Re-exports DatasetMapper

DatasetOptions

Re-exports DatasetOptions

DatasetReducer

Re-exports DatasetReducer

DatasetStats

Re-exports DatasetStats

defaultRoute

Re-exports defaultRoute

DefaultRouteUserData

DefaultStorageIdentifier

EnqueueLinksOptions

EnqueueStrategy

Re-exports EnqueueStrategy

EnqueueStrategyOption

EnqueueUrlsOptions

ErrnoException

Re-exports ErrnoException

ErrorHandler

Re-exports ErrorHandler

ErrorSnapshotter

Re-exports ErrorSnapshotter

ErrorTracker

Re-exports ErrorTracker

ErrorTrackerOptions

EventLoopLoadSignal

EventLoopLoadSignalOptions

EventManager

Re-exports EventManager

EventManagerOptions

EventStatusMessageData

EventType

Re-exports EventType

EventTypeName

Re-exports EventTypeName

ExplicitStorageIdentifier

ExtractLinksOptions

field

Re-exports field

FieldsInput

Re-exports FieldsInput

FieldsOutput

Re-exports FieldsOutput

FinalStatistics

Re-exports FinalStatistics

GetUserDataFromRequest

GlobInput

Re-exports GlobInput

GlobObject

Re-exports GlobObject

IConcurrencySystem

IProxyConfiguration

IRequestLoader

Re-exports IRequestLoader

IRequestManager

Re-exports IRequestManager

IStatistics

Re-exports IStatistics

IStorage

Re-exports IStorage

JournaledRequest

Re-exports JournaledRequest

JournalEntry

Re-exports JournalEntry

KeyConsumer

Re-exports KeyConsumer

KeyValueStore

Re-exports KeyValueStore

KeyValueStoreIteratorOptions

KeyValueStoreJournalEntry

KeyValueStoreOptions

KeyValueStoreRawRecord

KeyValueStoreStats

LabeledSource

Re-exports LabeledSource

LauncherBrowserPoolOptions

LauncherRemoteBrowserPoolOptions

LoadedRequest

Re-exports LoadedRequest

LoadSignal

Re-exports LoadSignal

LoadSignalInfo

Re-exports LoadSignalInfo

LoadSignalsOptions

LoadSignalStartContext

LoadSnapshot

Re-exports LoadSnapshot

LocalEventManager

LocalEventManagerOptions

log

Re-exports log

Log

Re-exports Log

Logger

Re-exports Logger

LoggerJson

Re-exports LoggerJson

LoggerOptions

Re-exports LoggerOptions

LoggerText

Re-exports LoggerText

LogLevel

Re-exports LogLevel

MAX_POOL_SIZE

Re-exports MAX_POOL_SIZE

MemoryLoadSignal

Re-exports MemoryLoadSignal

MemoryLoadSignalOptions

MemoryStorageBackend

MemoryStorageOptions

MissingSessionError

NavigationSkippedError

NonRetryableError

OwnedBrowserPool

Re-exports OwnedBrowserPool

PacingScope

Re-exports PacingScope

PacingSignal

Re-exports PacingSignal

parseRetryAfterHeader

parseValue

Re-exports parseValue

PERSIST_STATE_KEY

PersistenceOptions

PersistentRateLimitError

ProxyConfiguration

ProxyConfigurationFunction

ProxyConfigurationOptions

purgeDefaultStorages

PushErrorMessageOptions

RecordOptions

Re-exports RecordOptions

RecoverableState

Re-exports RecoverableState

RecoverableStateOptions

RecoverableStatePersistenceOptions

RegExpInput

Re-exports RegExpInput

RegExpObject

Re-exports RegExpObject

Request

Re-exports Request

RequestHandler

Re-exports RequestHandler

RequestHandlerError

RequestList

Re-exports RequestList

RequestListOptions

RequestListSourcesFunction

RequestListState

Re-exports RequestListState

RequestLoaderStatus

RequestManagerOpener

RequestManagerTandem

RequestOptions

Re-exports RequestOptions

RequestQueue

Re-exports RequestQueue

RequestQueueJournalEntry

RequestQueueOperationInfo

RequestQueueOperationOptions

RequestQueueOptions

RequestQueueStats

RequestsLike

Re-exports RequestsLike

RequestSourceStatus

RequestState

Re-exports RequestState

RequestThrottledError

RequestTransform

Re-exports RequestTransform

RequestValidationError

RequireContextPipeline

ResolvedConfigValues

resolveStorageIdentifier

ResponseLike

Re-exports ResponseLike

RestrictedCrawlingContext

RetryRequestError

RouteOptions

Re-exports RouteOptions

Router

Re-exports Router

RouterHandler

Re-exports RouterHandler

RouterHandlerContext

RouterLabel

Re-exports RouterLabel

RouterRoutes

Re-exports RouterRoutes

RouteSchemas

Re-exports RouteSchemas

RoutesFromSchemas

SchemaIssue

Re-exports SchemaIssue

serializeValue

Re-exports serializeValue

ServiceConflictError

serviceLocator

Re-exports serviceLocator

ServiceLocator

Re-exports ServiceLocator

Session

Re-exports Session

SessionError

Re-exports SessionError

SessionOptions

Re-exports SessionOptions

SessionPool

Re-exports SessionPool

SessionPoolOptions

SessionReuseStrategy

SitemapRequestLoader

SitemapRequestLoaderOptions

SkippedRequestCallback

SkippedRequestReason

SnapshotResult

Re-exports SnapshotResult

SnapshotStore

Re-exports SnapshotStore

Source

Re-exports Source

StateConversion

Re-exports StateConversion

StateValidationError

StatisticPersistedState

Statistics

Re-exports Statistics

StatisticsOptions

StatisticState

Re-exports StatisticState

StatisticStateExtensionOptions

StatusMessageCallback

StatusMessageCallbackParams

StorageBackend

Re-exports StorageBackend

StorageBackendLoadSignal

StorageBackendLoadSignalOptions

StorageIdentifier

StorageInstanceManager

StorageOpenOptions

StorageStatsTracker

StorageTransaction

StorageTransactionOptions

StorageTransactionState

StorageTransactionView

StorageWriteMode

Re-exports StorageWriteMode

StorageWritePolicy

SyncStateConversion

SystemInfo

Re-exports SystemInfo

TaskLoopOptions

Re-exports TaskLoopOptions

TaskLoopPredicates

ThrottlingRequestManager

ThrottlingRequestManagerOptions

TypedContextAddRequests

TypedContextEnqueueLinks

UrlPatternInput

Re-exports UrlPatternInput

UrlPatternObject

Re-exports UrlPatternObject

useState

Re-exports useState

UseStateOptions

Re-exports UseStateOptions

withDirectStorageAccess

WithRequired

Re-exports WithRequired

withStorageTransaction

externalAgentConfig

AgentConfig: { cua?: boolean; executionModel?: string | AgentModelConfig<string>; integrations?: (Client | string)[]; mode?: AgentToolMode; model?: string | AgentModelConfig<string>; stream?: boolean; systemPrompt?: string; tools?: ToolSet }

Type declaration

  • externaloptionalcua?: boolean

    Deprecated - Use mode: "cua" instead. This option will be removed in a future version. Enables Computer Use Agent (CUA) mode.

  • externaloptionalexecutionModel?: string | AgentModelConfig<string>

    The model to use for tool execution (observe/act calls within agent tools). If not specified, inherits from the main model configuration. Format: "provider/model" (e.g., "openai/gpt-4o-mini", "google/gemini-2.0-flash-exp")

  • externaloptionalintegrations?: (Client | string)[]

    MCP integrations - Array of Client objects

  • externaloptionalmode?: AgentToolMode

    Tool mode for the agent. Determines which set of tools are available.

    • 'dom' (default): Uses DOM-based tools (act, fillForm) for structured interactions
    • 'hybrid': Uses coordinate-based tools (click, type, dragAndDrop, clickAndHold, fillFormVision) for visual/screenshot-based interactions
    • 'cua': Uses Computer Use Agent (CUA) providers for screenshot-based automation
  • externaloptionalmodel?: string | AgentModelConfig<string>

    The model to use for agent functionality

  • externaloptionalstream?: boolean

    Enable streaming mode for the agent. When true, execute() returns AgentStreamResult with textStream for incremental output. When false (default), execute() returns AgentResult after completion.

  • externaloptionalsystemPrompt?: string

    Custom system prompt to provide to the agent. Overrides the default system prompt.

  • externaloptionaltools?: ToolSet

    Tools passed to the agent client

externalModelConfiguration

ModelConfiguration: AvailableModel | (ClientOptions & { modelName: AvailableModel })

StagehandBrowserPool

StagehandBrowserPool: BrowserPool<{ browserPlugins: [StagehandPlugin] }, [StagehandPlugin]>

A BrowserPool of Stagehand browsers, as built by stagehandBrowserPool.

StagehandGotoOptions

StagehandGotoOptions: NonNullable<Parameters<Page[goto]>[1]>

Goto options for StagehandCrawler navigation.

StagehandHook

StagehandHook<UserData>: BrowserHook<StagehandCrawlingContext<UserData>>

Hook function for StagehandCrawler.


Type parameters

Page Options