The observe() method identifies actionable elements on a page and returns Action objects that can be previewed, cached, or executed later with act(). This is useful for:
Returns a Promise<Action[]> - an array of Action objects:
interface Action { selector: string; // XPath selector for the element description: string; // Human-readable description method?: string; // Playwright method to use (click, fill, etc.) arguments?: string[]; // Arguments for the method}
// Find the actionconst [loginAction] = await stagehand.observe( "find the login button");// Review what will happenconsole.log("Will execute:", loginAction.description);console.log("Using method:", loginAction.method);// Confirm with user or validateconst userConfirmed = await promptUser( `Execute ${loginAction.description}?`);if (userConfirmed) { await stagehand.act(loginAction);}
// Observe only within a specific sectionconst sidebarActions = await stagehand.observe( "find navigation links", { selector: "aside.sidebar", });// Or use XPathconst formActions = await stagehand.observe( "find all form fields", { selector: "xpath=//form[@id='contact']", });
await page.goto("https://www.apartments.com/san-francisco-ca/");// Observe each steplet observation: Action;[observation] = await stagehand.observe( "find the 'all filters' button");await stagehand.act(observation);await new Promise((resolve) => setTimeout(resolve, 2000));[observation] = await stagehand.observe( "find the '1+' button in the 'beds' section");await stagehand.act(observation);await new Promise((resolve) => setTimeout(resolve, 2000));[observation] = await stagehand.observe( "find the 'apartments' button in the 'home type' section");await stagehand.act(observation);await new Promise((resolve) => setTimeout(resolve, 2000));[observation] = await stagehand.observe( "find the pet policy dropdown");await stagehand.act(observation);
const [action] = await stagehand.observe("find submit button");console.log(`Ready to: ${action.description}`);// User confirms, then executeawait stagehand.act(action);
// Cache during developmentconst actions = await stagehand.observe("find all buttons");saveToCache(actions);// Use in production without LLMconst cached = loadFromCache();await stagehand.act(cached[0]);