Manage the lifecycle of your Notte browser sessions
Every Notte session follows a predictable lifecycle from creation to termination. Understanding this lifecycle helps you build reliable automation workflows and manage resources effectively.
Here’s a complete example demonstrating best practices for session management:
Copy
Ask AI
from notte_sdk import NotteClientimport timeclient = NotteClient()def run_automation(): # 1. Create session with configuration print("Creating session...") with client.Session( headless=False, # Opens live viewer timeout_minutes=10, cookie_file="cookies.json" # Auto-load/save cookies ) as session: print(f"Session created: {session.session_id}") print("Live viewer opened in browser") # 2. Access Playwright page page = session.page # 3. Use the session print("Navigating to example.com...") page.goto("https://example.com") title = page.title() print(f"Page title: {title}") # Take a screenshot page.screenshot(path="screenshot.png") print("Screenshot saved") # Wait before closing time.sleep(3) # Cookies automatically saved to cookies.json print("Session will be stopped and cookies saved...") # Session automatically stopped here print("Session stopped successfully")if __name__ == "__main__": run_automation()
You can reconnect to an existing session using its session_id:
Copy
Ask AI
from notte_sdk import NotteClientclient = NotteClient()# Connect to existing sessionsession_id = "550e8400-e29b-41d4-a716-446655440000"with client.Session(session_id) as session: print(f"Connected to session: {session.session_id}") # Get current status status = session.status() print(f"Session status: {status.status}") # Continue using the session page = session.page page.goto("https://example.com")
The context manager automatically handles cleanup, even when errors occur:
Copy
Ask AI
from notte_sdk import NotteClientclient = NotteClient()try: with client.Session() as session: page = session.page page.goto("https://example.com") # Simulate an error raise ValueError("Something went wrong!")except ValueError as e: print(f"Automation failed: {e}") # Session is still automatically stoppedprint("Session was cleaned up despite the error")
Check session status before long-running operations:
Copy
Ask AI
with client.Session() as session: status = session.status() if status.status != 'active': raise Exception('Session is no longer active') # Continue with operations