Skip to main content

Python SDK for Stagehand

Project description

Stagehand Python SDK

A Python SDK for Stagehand, enabling automated browser control and data extraction.

Installation```bash

pip install stagehand-py


## Quickstart

Before running your script, make sure you have exported the necessary environment variables:

```bash
export BROWSERBASE_API_KEY="your-api-key"
export BROWSERBASE_PROJECT_ID="your-project-id"
export OPENAI_API_KEY="your-openai-api-key"
export SERVER_URL="url-of-stagehand-server" 

Usage

Here is a minimal example to get started:

import asyncio
import os
from stagehand.client import Stagehand
from dotenv import load_dotenv

load_dotenv()

async def log_handler(log_data: dict):
    """
    Enhanced async log handler that shows more detailed server logs.
    """
    # Print the full log data structure
    if "type" in log_data:
        log_type = log_data["type"]
        data = log_data.get("data", {})
        
        if log_type == "system":
            print(f"🔧 SYSTEM: {data}")
        elif log_type == "log":
            print(f"📝 LOG: {data}")
        else:
            print(f"ℹ️ OTHER [{log_type}]: {data}")
    else:
        # Fallback for any other format
        print(f"🤖 RAW LOG: {log_data}")

async def main():
    # Create a Stagehand client - it will create a new session automatically
    stagehand = Stagehand(
        server_url=os.getenv("SERVER_URL"),
        browserbase_api_key=os.getenv("BROWSERBASE_API_KEY"),
        browserbase_project_id=os.getenv("BROWSERBASE_PROJECT_ID"),
        openai_api_key=os.getenv("OPENAI_API_KEY"),
        on_log=log_handler,  # attach the log handler to receive streaming logs
        verbose=2,
        model_name="gpt-4o",  # optional - defaults to server's default
        dom_settle_timeout_ms=3000,  # optional - defaults to server's default
        debug_dom=True,  # optional - defaults to server's default
    )


    # Initialize - this will create a new session
    await stagehand.page.init()
    print(f"Created new session: {stagehand.session_id}")

    # Example: navigate to google.com
    await stagehand.page.navigate("https://www.google.com")
    print("Navigation complete.")

    # Example: ACT to do something like 'search for openai'
    result = await stagehand.page.act("search for openai")
    print("Action result:", result)

    # Close the session (if needed)
    await stagehand.close()
if __name__ == "__main__":
    asyncio.run(main())

Configuration

  • server_url: The Stagehand server URL (default: http://localhost:3000)
  • browserbase_api_key: Your BrowserBase API key (can also be set via BROWSERBASE_API_KEY environment variable)
  • browserbase_project_id: Your BrowserBase project ID (can also be set via BROWSERBASE_PROJECT_ID environment variable)
  • openai_api_key: Your OpenAI API key (can also be set via OPENAI_API_KEY environment variable)
  • verbose: Verbosity level (default: 1)
  • model_name: (optional) Model name to use for the conversation
  • dom_settle_timeout_ms: (optional) Additional time for the DOM to settle
  • debug_dom: (optional) Whether or not to enable DOM debug mode

Features

  • Automated browser control with natural language commands
  • Data extraction with schema validation (either pydantic or JSON schema)
  • Async/await support
  • Extension of Playwright - run playwright commands normally, with act/extract/observe offloaded to an API

Requirements

  • Python 3.7+
  • httpx
  • asyncio
  • pydantic
  • python-dotenv (optional if using a .env file)

License

MIT License (c) Browserbase, Inc.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stagehand_py-0.1.6.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stagehand_py-0.1.6-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file stagehand_py-0.1.6.tar.gz.

File metadata

  • Download URL: stagehand_py-0.1.6.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.21

File hashes

Hashes for stagehand_py-0.1.6.tar.gz
Algorithm Hash digest
SHA256 fd3f0ccd5e55c4d6c6b698eedf0acbded38ccd25083e38782c19a81d40f3e469
MD5 32f18affce859b8fefa200481c5a2910
BLAKE2b-256 c2b450877642076438e309b7f27fe6bfb475fa27c79a56fa0b3eb13371cf305a

See more details on using hashes here.

File details

Details for the file stagehand_py-0.1.6-py3-none-any.whl.

File metadata

  • Download URL: stagehand_py-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.21

File hashes

Hashes for stagehand_py-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 115daef2e9b9996f2882f649a1673c6f6a881bc903a52a6254312fc9dcc9b7b4
MD5 59d5be526e660cca6688d0921598f93e
BLAKE2b-256 8dc63bcb6f4b4a0fdaa01aad4f251fbb7295d2ab7136d6b7774abfc59bfdda3d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page