Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

backwards compatibility with old models and improved tests with icognito mode

Nick Sweeting15a760ef1767
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index c9cdfa9f0..6085cc44b 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -1,3 +1,8 @@
-from browser_use.browser.compat import Browser, BrowserConfig, BrowserContext, BrowserContextConfig
+from browser_use.browser.session import BrowserSession
+from browser_use.browser.types import BrowserProfile
-__all__ = ['Browser', 'BrowserConfig', 'BrowserContext', 'BrowserContextConfig']
+BrowserConfig = BrowserProfile
+BrowserContextConfig = BrowserProfile
+Browser = BrowserSession
+
+__all__ = ['BrowserConfig', 'BrowserContextConfig', 'Browser']
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index c9cdfa9f0..4340e4508 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -1,3 +1,9 @@
-from browser_use.browser.compat import Browser, BrowserConfig, BrowserContext, BrowserContextConfig
+from browser_use.browser.session import BrowserSession
+from browser_use.browser.types import BrowserProfile
+
+Browser = BrowserSession
+BrowserConfig = BrowserProfile
+BrowserContext = BrowserSession
+BrowserContextConfig = BrowserProfile
__all__ = ['Browser', 'BrowserConfig', 'BrowserContext', 'BrowserContextConfig']
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index fd757cc61..73800e356 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -233,6 +233,10 @@ class BrowserSession(BaseModel):
"""Shortcut for self.stop()"""
await self.stop()
+ async def new_context(self, **kwargs):
+ """Create a new browser context with the given kwargs"""
+ return self
+
async def __aenter__(self) -> BrowserSession:
await self.start()
return self
@@ -316,7 +320,9 @@ class BrowserSession(BaseModel):
# if we still have no browser_context by now, launch a new local one using launch_persistent_context()
if not self.browser_context:
- logger.info(f'🌎 Launching local playwright chromium context with user_data_dir={self.browser_profile.user_data_dir}')
+ logger.info(
+ f'🌎 Launching local {str(type(self.playwright).__module__).split(".")[0]} {self.browser_profile.channel.name.lower()} context with user_data_dir={self.browser_profile.user_data_dir or "<tmp incognito>"}'
+ )
if not self.browser_profile.user_data_dir:
# if no user_data_dir is provided, launch an incognito context with no persistent user_data_dir
self.browser = self.browser or await self.playwright.chromium.launch(
@@ -327,6 +333,7 @@ class BrowserSession(BaseModel):
)
else:
# if a user_data_dir is provided, launch a persistent context with that user_data_dir
+ self.browser_profile.prepare_user_data_dir()
self.browser_context = await self.playwright.chromium.launch_persistent_context(
**self.browser_profile.kwargs_for_launch_persistent_context().model_dump()
)
diff --git a/browser_use/browser/types.py b/browser_use/browser/types.py
index eab88a384..5d250a534 100644
--- a/browser_use/browser/types.py
+++ b/browser_use/browser/types.py
@@ -382,7 +382,7 @@ class BrowserConnectArgs(BaseModel):
model_config = ConfigDict(extra='ignore', validate_assignment=True, revalidate_instances='always', populate_by_name=True)
- headers: dict[str, str] = Field(default_factory=dict)
+ headers: dict[str, str] | None = Field(default=None, description='Additional HTTP headers to be sent with connect request')
slow_mo: float = 0.0
timeout: float = 30_000
diff --git a/browser_use/dom/tests/debug_page_structure.py b/tests/debug_page_structure.py
similarity index 99%
rename from browser_use/dom/tests/debug_page_structure.py
rename to tests/debug_page_structure.py
index 49e99bbc2..43d9658d9 100644
--- a/browser_use/dom/tests/debug_page_structure.py
+++ b/tests/debug_page_structure.py
@@ -13,7 +13,8 @@ async def analyze_page_structure(url: str):
browser = Browser(
config=BrowserConfig(
headless=False, # Set to True if you don't need to see the browser
- )
+ ),
+ user_data_dir=None,
)
context = BrowserContext(browser=browser)
diff --git a/browser_use/dom/tests/extraction_test.py b/tests/extraction_test.py
similarity index 100%
rename from browser_use/dom/tests/extraction_test.py
rename to tests/extraction_test.py
diff --git a/browser_use/browser/tests/httpx_client_test.py b/tests/httpx_client_test.py
similarity index 100%
rename from browser_use/browser/tests/httpx_client_test.py
rename to tests/httpx_client_test.py
diff --git a/browser_use/dom/tests/process_dom_test.py b/tests/process_dom_test.py
similarity index 100%
rename from browser_use/dom/tests/process_dom_test.py
rename to tests/process_dom_test.py
diff --git a/browser_use/browser/tests/screenshot_test.py b/tests/screenshot_test.py
similarity index 100%
rename from browser_use/browser/tests/screenshot_test.py
rename to tests/screenshot_test.py
diff --git a/tests/test_browser.py b/tests/test_browser.py
index 57025af87..9d3874a17 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -1,48 +1,25 @@
import pytest
+from playwright.async_api import async_playwright
-from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser import BrowserSession
@pytest.mark.asyncio
-async def test_builtin_browser_launch(monkeypatch):
- """
- Test that the standard browser is launched correctly.
- This test monkeypatches async_playwright to return dummy objects, and asserts that BrowserSession.initialize() returns the expected browser.
- """
+async def test_connection_via_cdp(monkeypatch):
+ browser_session = BrowserSession(
+ cdp_url='http://localhost:9222',
+ )
+ with pytest.raises(Exception) as e:
+ await browser_session.start()
+ assert 'Failed to connect to browser' in str(e)
- class DummyBrowser:
- pass
+ playwright = await async_playwright().start()
+ browser = await playwright.chromium.launch(args=['--remote-debugging-port=9222'])
- class DummyChromium:
- async def launch(self, headless, args, proxy=None, handle_sigterm=False, handle_sigint=False):
- return DummyBrowser()
+ await browser_session.start()
+ await browser_session.create_new_tab()
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
+ assert (await browser_session.get_current_page()).url == 'about:blank'
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.session.async_playwright', lambda: DummyAsyncPlaywrightContext())
- session = BrowserSession(headless=True, disable_security=False, extra_launch_args=['--test'])
- await session.initialize()
- assert isinstance(session.browser, DummyBrowser), 'Expected DummyBrowser from _launch_browser'
- await session.close()
-
-
-async def test_new_context_creation():
- """
- Test that the BrowserSession is initialized with the correct attributes.
- This verifies that the BrowserSession is initialized with the provided profile configuration.
- """
- profile = BrowserProfile()
- session = BrowserSession(profile=profile)
- await session.initialize()
- assert session.profile == profile, "Expected the session's profile to be the provided profile"
- await session.close()
+ await browser_session.close()
+ await browser.close()
diff --git a/tests/test_browser_session.py b/tests/test_browser_session.py
index b292ed4f5..d1229561f 100644
--- a/tests/test_browser_session.py
+++ b/tests/test_browser_session.py
@@ -68,7 +68,6 @@ class TestBrowserContext:
# browser_profile=BrowserProfile(...),
headless=True,
user_data_dir=None,
- disable_security=False,
)
await browser_session.start()
yield browser_session
diff --git a/browser_use/browser/tests/test_clicks.py b/tests/test_clicks.py
similarity index 98%
rename from browser_use/browser/tests/test_clicks.py
rename to tests/test_clicks.py
index c85faee2c..eb6182d95 100644
--- a/browser_use/browser/tests/test_clicks.py
+++ b/tests/test_clicks.py
@@ -31,7 +31,7 @@ class ElementTreeSerializer:
# run with: pytest browser_use/browser/tests/test_clicks.py
@pytest.mark.asyncio
async def test_highlight_elements():
- browser = Browser(config=BrowserConfig(headless=False, disable_security=True))
+ browser = Browser(config=BrowserConfig(headless=False, disable_security=True, user_data_dir=None))
async with await browser.new_context() as context:
page = await context.get_current_page()
diff --git a/tests/test_controller.py b/tests/test_controller.py
index af8014c45..fbd1055ab 100644
--- a/tests/test_controller.py
+++ b/tests/test_controller.py
@@ -6,7 +6,7 @@ from pydantic import BaseModel
from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel, ActionResult
-from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser import BrowserSession
from browser_use.controller.service import Controller
from browser_use.controller.views import (
ClickElementAction,
@@ -85,9 +85,8 @@ class TestControllerIntegration:
async def browser_session(self, event_loop):
"""Create and provide a Browser instance with security disabled."""
browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=True,
- ),
+ # browser_profile=BrowserProfile(),
+ headless=True,
user_data_dir=None,
)
await browser_session.start()