Skip to content

browserbase/stagehand-python

Repository files navigation

The AI Browser Automation Framework
Read the Docs

PyPI version MIT License Slack Community

Stagehand Python is now available! We're actively seeking feedback from the community and looking for contributors. Join our Slack community to stay updated on the latest updates

Why Stagehand?

Stagehand is the easiest way to build browser automations with AI-powered interactions.

Most existing browser automation tools either require you to write low-level code in a framework like Selenium, Playwright, or Puppeteer, or use high-level agents that can be unpredictable in production. By letting developers choose what to write in code vs. natural language, Stagehand is the natural choice for browser automations in production.

  1. Choose when to write code vs. natural language: use AI when you want to navigate unfamiliar pages, and use code (Playwright) when you know exactly what you want to do.

  2. Preview and cache actions: Stagehand lets you preview AI actions before running them, and also helps you easily cache repeatable actions to save time and tokens.

  3. Computer use models with one line of code: Stagehand lets you integrate SOTA computer use models from OpenAI and Anthropic into the browser with one line of code.


TL;DR: Automate the web reliably with natural language:

  • act — Instruct the AI to perform actions (e.g. click a button or scroll).
await stagehand.page.act("click on the 'Quickstart' button")
  • extract — Extract and validate data from a page using a Pydantic schema.
await stagehand.page.extract("the summary of the first paragraph")
  • observe — Get natural language interpretations to, for example, identify selectors or elements from the page.
await stagehand.page.observe("find the search bar")
  • agent — Execute autonomous multi-step tasks with provider-specific agents (OpenAI, Anthropic, etc.).
await stagehand.agent.execute("book a reservation for 2 people for a trip to the Maldives")

Installation:

To get started, simply:

pip install stagehand

We recommend using uv for your package/project manager. If you're using uv can follow these steps:

uv venv .venv
source .venv/bin/activate
uv pip install stagehand

Quickstart

import asyncio
import os
from dotenv import load_dotenv
from pydantic import BaseModel, Field

from stagehand import StagehandConfig, Stagehand

# Load environment variables
load_dotenv()

# Define Pydantic models for structured data extraction
class Company(BaseModel):
    name: str = Field(..., description="Company name")
    description: str = Field(..., description="Brief company description")

class Companies(BaseModel):
    companies: list[Company] = Field(..., description="List of companies")
    
async def main():
    # Create configuration
    config = StagehandConfig(
        env = "BROWSERBASE", # or LOCAL
        api_key=os.getenv("BROWSERBASE_API_KEY"),
        project_id=os.getenv("BROWSERBASE_PROJECT_ID"),
        model_name="google/gemini-2.5-flash-preview-05-20",
        model_client_options={"apiKey": os.getenv("MODEL_API_KEY")},
    )
    
    stagehand = Stagehand(config)
    
    try:
        print("\nInitializing 🤘 Stagehand...")
        # Initialize Stagehand
        await stagehand.init()

        if stagehand.env == "BROWSERBASE":    
            print(f"🌐 View your live browser: https://www.browserbase.com/sessions/{stagehand.session_id}")

        page = stagehand.page

        await page.goto("https://www.aigrant.com")
        
        # Extract companies using structured schema        
        companies_data = await page.extract(
          "Extract names and descriptions of 5 companies in batch 3",
          schema=Companies
        )
        
        # Display results
        print("\nExtracted Companies:")
        for idx, company in enumerate(companies_data.companies, 1):
            print(f"{idx}. {company.name}: {company.description}")

        observe = await page.observe("the link to the company Browserbase")
        print("\nObserve result:", observe)
        act = await page.act("click the link to the company Browserbase")
        print("\nAct result:", act)
            
    except Exception as e:
        print(f"Error: {str(e)}")
        raise
    finally:
        # Close the client
        print("\nClosing 🤘 Stagehand...")
        await stagehand.close()

if __name__ == "__main__":
    asyncio.run(main())

Documentation

See our full documentation here.

Cache Actions

You can cache actions in Stagehand to avoid redundant LLM calls. This is particularly useful for actions that are expensive to run or when the underlying DOM structure is not expected to change.

Using observe to preview an action

observe lets you preview an action before taking it. If you are satisfied with the action preview, you can run it in page.act with no further LLM calls.

# Get the action preview
action_preview = await page.observe("Click the quickstart link")

# action_preview is a JSON-ified version of a Playwright action:
# {
#     "description": "The quickstart link",
#     "method": "click",
#     "selector": "/html/body/div[1]/div[1]/a",
#     "arguments": []
# }

# NO LLM INFERENCE when calling act on the preview
await page.act(action_preview[0])

If the website happens to change, self_heal will run the loop again to save you from constantly updating your scripts.

Contributing

At a high level, we're focused on improving reliability, speed, and cost in that order of priority. If you're interested in contributing, reach out on Slack, open an issue or start a discussion.

For more info, check the Contributing Guide.

Local Development Installation:

# Clone the repository
git clone https://github.com/browserbase/stagehand-python.git
cd stagehand-python

# Install in editable mode with development dependencies
pip install -r requirements.txt

License

MIT License (c) 2025 Browserbase, Inc.

About

The AI Browser Automation Framework

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published