Implement the main execution function with comprehensive error handling:
main.py
Copy
Ask AI
async def main(): try: session = await create_browserbase_session() browser_profile = create_browser_profile() task = ("Go to https://www.macrumors.com/contact.php and fill in the form. " "Make sure to use the selectors and submit the form") async with ManagedBrowserSession(session.connect_url, browser_profile) as browser_session: result = await run_automation_task(browser_session, task) print(f"Final result: {result}") except KeyboardInterrupt: print("\nâšī¸ Process interrupted by user") except Exception as e: print(f"đĨ Fatal error: {e}") raise finally: print("đ Application shutdown complete")if __name__ == "__main__": asyncio.run(main())
7
Run your script
Run your script:
Copy
Ask AI
uv run main.py
You should see your Browserbase session start in Browserbase. The debug URL will be printed to console for real-time session monitoring.
Important Environment VariablesMake sure you have these environment variables in your .env file:
BROWSERBASE_API_KEY
BROWSERBASE_PROJECT_ID
OPENAI_API_KEY
Key Features of This Implementation
Clean Resource Management: Context manager ensures proper cleanup without complexity
Essential Error Handling: Handles browser disconnections and cleanup failures gracefully
Simplified Approach: Focused on core functionality without unnecessary overhead
Production Ready: Robust enough for real-world applications
Browser Use Best Practices Implemented
Set keep_alive=False for proper session cleanup
Use reasonable timeouts to prevent hanging processes
Implement proper Playwright instance cleanup
Handle expected browser disconnections after task completion
Use structured error handling with clear logging
Common Issues & Fixes
Browser disconnection after successful form submission is expected behavior
The context manager ensures proper cleanup even if errors occur