Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
try to shutdown global playwright object atexit
Nick Sweeting110e7962ad0f
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex a85a55b3b..4b6746732 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import atexitimport base64import jsonimport logging@@ -259,13 +260,13 @@ class BrowserSession(BaseModel):"""Starts the browser session by either connecting to an existing browser or launching a new one.Precedence order for launching/connecting:- 1. page=Page playwright object, will use its page.context as browser_context- 2. browser_context=PlaywrightBrowserContext object, will use its browser- 3. browser=PlaywrightBrowser object, will use its first available context- 4. browser_pid=int, will connect to a local chromium-based browser via pid- 5. wss_url=str, will connect to a remote playwright browser server via WSS- 6. cdp_url=str, will connect to a remote chromium-based browser via CDP- 7. playwright=Playwright object, will use its chromium instance to launch a new browser+ 1. page=Page playwright object, will use its page.context as browser_context+ 2. browser_context=PlaywrightBrowserContext object, will use its browser+ 3. browser=PlaywrightBrowser object, will use its first available context+ 4. browser_pid=int, will connect to a local chromium-based browser via pid+ 5. wss_url=str, will connect to a remote playwright browser server via WSS+ 6. cdp_url=str, will connect to a remote chromium-based browser via CDP+ 7. playwright=Playwright object, will use its chromium instance to launch a new browser"""# if we're already initialized and the connection is still valid, return the existing session state and start from scratch@@ -630,6 +631,21 @@ class BrowserSession(BaseModel):if self.browser_profile.headless or not self.browser_profile.no_viewport:self.logger.info(' 🪄 For maximum stealth, BrowserSession(...) should be passed headless=False & viewport=None')+ # register a shutdown hook to stop the shared global playwright node.js client when the program exits (if an event loop is still running)+ def shudown_playwright():+ if not self.playwright:+ return+ try:+ loop = asyncio.get_running_loop()+ self.logger.debug('🛑 Shutting down shared global playwright node.js client')+ task = loop.create_task(self.playwright.stop())+ if hasattr(task, '_log_destroy_pending'):+ task._log_destroy_pending = False # type: ignore+ except Exception:+ pass++ atexit.register(shudown_playwright)+async def setup_browser_via_passed_objects(self) -> None:"""Override to customize the set up of the connection to an existing browser"""diff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.pyindex 283366b7d..7c682af2a 100644--- a/tests/ci/test_browser_session_start.py+++ b/tests/ci/test_browser_session_start.py@@ -13,6 +13,7 @@ import asyncioimport jsonimport loggingfrom pathlib import Path+import tempfileimport pytest@@ -573,53 +574,6 @@ class TestBrowserSessionStart:class TestBrowserSessionReusePatterns:"""Tests for all browser re-use patterns documented in docs/customize/real-browser.mdx"""- @pytest.fixture(scope='module')- def mock_llm(self):- """Mock LLM for agent tests"""- from unittest.mock import MagicMock-- from langchain_core.language_models.chat_models import BaseChatModel-- # Create a MagicMock that supports dictionary-style access- mock = MagicMock(spec=BaseChatModel)-- # Skip verification by setting these attributes- mock._verified_api_keys = True- mock._verified_tool_calling_method = 'raw'- mock.model_name = 'mock-llm'-- # Mock the invoke method to return a proper response- def mock_invoke(*args, **kwargs):- response = MagicMock()- # Return a valid JSON response that completes the task- response.content = """- {- "thinking": "null",- "evaluation_previous_goal": "Starting the task",- "memory": "Task started",- "next_goal": "Complete the task",- "action": [- {- "done": {- "text": "Task completed successfully",- "success": true- }- }- ]- }- """- return response-- mock.invoke = mock_invoke-- # Create an async version of the mock_invoke- async def mock_ainvoke(*args, **kwargs):- return mock_invoke(*args, **kwargs)-- mock.ainvoke = mock_ainvoke-- return mock-async def test_sequential_agents_same_profile_different_browser(self, mock_llm):"""Test Sequential Agents, Same Profile, Different Browser pattern"""from browser_use import Agent