Stagehand operates through sessions. A typical workflow involves starting a session, navigating to a URL, and then performing actions like observing, acting, extracting, or executing instructions.
Key session methods include:
client.sessions.start(...): Initializes a session with a specific model and browser type.client.sessions.navigate(session_id, url=...): Navigates the session to a URL.client.sessions.observe(...): Observes the page based on an instruction.client.sessions.act(...): Performs an action (e.g., clicking) based on natural language input.client.sessions.extract(...): Extracts structured data from the page using a provided schema.client.sessions.execute(...): Runs an agentic workflow to complete a complex task.client.sessions.end(session_id): Ends the session.
import os
from playwright.sync_api import sync_playwright
from stagehand import Stagehand
def main() -> None:
with Stagehand(
server="remote",
browserbase_api_key=os.environ.get("BROWSERBASE_API_KEY"),
model_api_key=os.environ.get("MODEL_API_KEY"),
) as client:
session = client.sessions.start(
model_name="anthropic/claude-sonnet-4-6",
browser={"type": "browserbase"},
)
cdp_url = session.data.cdp_url
with sync_playwright() as p:
browser = p.chromium.connect_over_cdp(cdp_url)
page = browser.new_page()
client.sessions.navigate(session.id, url="https://news.ycombinator.com")
# Example: Observe
observe_stream = client.sessions.observe(
session.id,
instruction="find the link to view comments for the top post",
stream_response=True,
x_stream_response="true",
)
# Example: Act
act_stream = client.sessions.act(
session.id,
input="Click the comments link for the top post",
stream_response=True,
x_stream_response="true",
)
# Example: Extract
extract_stream = client.sessions.extract(
session.id,
instruction="extract the text of the top comment on this page",
schema={
"type": "object",
"properties": {
"commentText": {"type": "string"},
"author": {"type": "string"},
},
"required": ["commentText"],
},
stream_response=True,
x_stream_response="true",
)
# Example: Execute
execute_stream = client.sessions.execute(
session.id,
execute_options={
"instruction": "Click the 'Learn more' link if available",
"max_steps": 3,
},
agent_config={
"model": {"model_name": "anthropic/claude-opus-4-6"},
"cua": False,
},
stream_response=True,
x_stream_response="true",
)
client.sessions.end(session.id)