Basic Usage
Copy
Ask AI
import os
import asyncio
import aiohttp
import ssl
from typing import Optional, Dict, Any
from stagehand import Stagehand
ssl._create_default_https_context = ssl._create_unverified_context
API_KEY = os.environ.get("ANCHOR_API_KEY")
if not API_KEY:
raise ValueError("ANCHOR_API_KEY is not set")
async def create_browser_session() -> Dict[str, Any]:
async with aiohttp.ClientSession() as session:
async with session.post(
"https://api.anchorbrowser.io/v1/sessions",
headers={
"anchor-api-key": API_KEY,
"Content-Type": "application/json",
},
json={
"session": {
"proxy": {"active": True}
},
"browser": {
"extra_stealth": {"active": True}
}
},
ssl=False
) as response:
if not response.ok:
raise Exception(f"Failed to create session: {response.status}")
return (await response.json())["data"]
async def stop_browser_session(session_id: str):
async with aiohttp.ClientSession() as session:
async with session.delete(
f"https://api.anchorbrowser.io/v1/sessions/{session_id}",
headers={"anchor-api-key": API_KEY},
ssl=False
) as response:
if response.ok:
print(f"Session {session_id} stopped")
async def run_stagehand():
session_id: Optional[str] = None
stagehand: Optional[Stagehand] = None
try:
session = await create_browser_session()
session_id = session["id"]
cdp_url = session["cdp_url"]
# Check for GOOGLE_API_KEY
google_api_key = os.environ.get("GOOGLE_API_KEY")
if not google_api_key:
raise ValueError("Either GOOGLE_API_KEY must be set")
stagehand = Stagehand(
verbose=1,
log_level="info",
dom_settle_timeout_ms=60000,
model_name="google/gemini-2.5-pro",
env="LOCAL",
local_browser_launch_options={"cdp_url": cdp_url}
)
await stagehand.init()
await stagehand.page.goto("https://example.com")
await stagehand.page.act("Click on Learn more link")
print(f"Current URL: {stagehand.page.url}")
finally:
if stagehand and not stagehand._closed:
await stagehand.close()
if session_id:
await stop_browser_session(session_id)
asyncio.run(run_stagehand())
Set
GOOGLE_API_KEY (or your LLM API key) in your environment variables for Stagehand to function.
