-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.py
137 lines (116 loc) · 4.57 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import asyncio
import logging
import os
from rich.console import Console
from rich.panel import Panel
from rich.theme import Theme
import json
from dotenv import load_dotenv
from stagehand import Stagehand, StagehandConfig
from stagehand.utils import configure_logging
# Configure logging with cleaner format
configure_logging(
level=logging.INFO,
remove_logger_name=True, # Remove the redundant stagehand.client prefix
quiet_dependencies=True, # Suppress httpx and other noisy logs
)
# Create a custom theme for consistent styling
custom_theme = Theme(
{
"info": "cyan",
"success": "green",
"warning": "yellow",
"error": "red bold",
"highlight": "magenta",
"url": "blue underline",
}
)
# Create a Rich console instance with our theme
console = Console(theme=custom_theme)
load_dotenv()
console.print(
Panel.fit(
"[yellow]Logging Levels:[/]\n"
"[white]- Set [bold]verbose=0[/] for errors (ERROR)[/]\n"
"[white]- Set [bold]verbose=1[/] for minimal logs (INFO)[/]\n"
"[white]- Set [bold]verbose=2[/] for medium logs (WARNING)[/]\n"
"[white]- Set [bold]verbose=3[/] for detailed logs (DEBUG)[/]",
title="Verbosity Options",
border_style="blue",
)
)
async def main():
# Build a unified configuration object for Stagehand
config = StagehandConfig(
env="BROWSERBASE",
api_key=os.getenv("BROWSERBASE_API_KEY"),
project_id=os.getenv("BROWSERBASE_PROJECT_ID"),
headless=False,
dom_settle_timeout_ms=3000,
model_name="gpt-4o",
self_heal=True,
wait_for_captcha_solves=True,
system_prompt="You are a browser automation assistant that helps users navigate websites effectively.",
model_client_options={"apiKey": os.getenv("MODEL_API_KEY")},
# Use verbose=2 for medium-detail logs (1=minimal, 3=debug)
verbose=2,
)
stagehand = Stagehand(
config=config,
server_url=os.getenv("STAGEHAND_SERVER_URL"),
)
# Initialize - this creates a new session automatically.
console.print("\n🚀 [info]Initializing Stagehand...[/]")
await stagehand.init()
page = stagehand.page
console.print(f"\n[yellow]Created new session:[/] {stagehand.session_id}")
console.print(
f"🌐 [white]View your live browser:[/] [url]https://www.browserbase.com/sessions/{stagehand.session_id}[/]"
)
await asyncio.sleep(2)
console.print("\n▶️ [highlight] Navigating[/] to Google")
await page.goto("https://google.com/")
console.print("✅ [success]Navigated to Google[/]")
console.print("\n▶️ [highlight] Clicking[/] on About link")
# Click on the "About" link using Playwright
await page.get_by_role("link", name="About", exact=True).click()
console.print("✅ [success]Clicked on About link[/]")
await asyncio.sleep(2)
console.print("\n▶️ [highlight] Navigating[/] back to Google")
await page.goto("https://google.com/")
console.print("✅ [success]Navigated back to Google[/]")
console.print("\n▶️ [highlight] Performing action:[/] search for openai")
await page.act("search for openai")
await page.keyboard.press("Enter")
console.print("✅ [success]Performing Action:[/] Action completed successfully")
await asyncio.sleep(2)
console.print("\n▶️ [highlight] Observing page[/] for news button")
observed = await page.observe("find the news button on the page")
if len(observed) > 0:
element = observed[0]
console.print("✅ [success]Found element:[/] News button")
console.print("\n▶️ [highlight] Performing action on observed element")
await page.act(element)
console.print("✅ [success]Performing Action:[/] Action completed successfully")
else:
console.print("❌ [error]No element found[/]")
console.print("\n▶️ [highlight] Extracting[/] first search result")
data = await page.extract("extract the first result from the search")
console.print("📊 [info]Extracted data:[/]")
console.print_json(f"{data.model_dump_json()}")
# Close the session
console.print("\n⏹️ [warning]Closing session...[/]")
await stagehand.close()
console.print("✅ [success]Session closed successfully![/]")
console.rule("[bold]End of Example[/]")
if __name__ == "__main__":
# Add a fancy header
console.print(
"\n",
Panel.fit(
"[light_gray]Stagehand 🤘 Python Example[/]",
border_style="green",
padding=(1, 10),
),
)
asyncio.run(main())