Skip to content

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

rename session.py profile.py, fix stealth example, fix tests

Nick Sweeting2f002b4c22f0
diff --git a/browser_use/__init__.py b/browser_use/__init__.py
index 87ec8ad42..4a9f3400e 100644
--- a/browser_use/__init__.py
+++ b/browser_use/__init__.py
@@ -13,8 +13,7 @@ setup_logging()
from browser_use.agent.prompts import SystemPrompt
from browser_use.agent.service import Agent
from browser_use.agent.views import ActionModel, ActionResult, AgentHistoryList
-from browser_use.browser import BrowserProfile, BrowserSession
-from browser_use.browser.compat import Browser, BrowserConfig, BrowserContext, BrowserContextConfig
+from browser_use.browser import Browser, BrowserConfig, BrowserContext, BrowserContextConfig, BrowserProfile, BrowserSession
from browser_use.controller.service import Controller
from browser_use.dom.service import DomService
diff --git a/browser_use/browser/__init__.py b/browser_use/browser/__init__.py
index 487a6641e..eaea05808 100644
--- a/browser_use/browser/__init__.py
+++ b/browser_use/browser/__init__.py
@@ -1,11 +1,6 @@
-"""
-Browser abstraction for Playwright powered by LLMs.
-"""
-
-# New API (use these moving forward)
-# Legacy API (for backward compatibility)
-from .compat import Browser, BrowserConfig, BrowserContext, BrowserContextConfig
+from .browser import Browser, BrowserConfig
+from .context import BrowserContext, BrowserContextConfig
+from .profile import BrowserProfile
from .session import BrowserSession
-from .types import BrowserProfile
__all__ = ['Browser', 'BrowserConfig', 'BrowserContext', 'BrowserContextConfig', 'BrowserSession', 'BrowserProfile']
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index 6085cc44b..e7a0653c3 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -1,5 +1,5 @@
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
-from browser_use.browser.types import BrowserProfile
BrowserConfig = BrowserProfile
BrowserContextConfig = BrowserProfile
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 4340e4508..990c14c5b 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -1,5 +1,5 @@
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
-from browser_use.browser.types import BrowserProfile
Browser = BrowserSession
BrowserConfig = BrowserProfile
diff --git a/browser_use/browser/types.py b/browser_use/browser/profile.py
similarity index 98%
rename from browser_use/browser/types.py
rename to browser_use/browser/profile.py
index 9c2715004..e2a0e8da2 100644
--- a/browser_use/browser/types.py
+++ b/browser_use/browser/profile.py
@@ -79,6 +79,7 @@ CHROME_DISABLED_COMPONENTS = [
'CrashReporting',
'OverscrollHistoryNavigation',
'InfiniteSessionRestore',
+ 'ExtensionDisableUnsupportedDeveloper',
]
CHROME_HEADLESS_ARGS = [
@@ -108,11 +109,11 @@ CHROME_DISABLE_SECURITY_ARGS = [
CHROME_DETERMINISTIC_RENDERING_ARGS = [
'--deterministic-mode',
'--js-flags=--random-seed=1157259159',
- # '--force-device-scale-factor=1',
- # '--enable-webgl',
+ '--force-device-scale-factor=1',
+ '--enable-webgl',
# '--disable-skia-runtime-opts',
# '--disable-2d-canvas-clip-aa',
- # '--font-render-hinting=none',
+ '--font-render-hinting=none',
'--force-color-profile=srgb',
]
@@ -152,6 +153,7 @@ CHROME_DEFAULT_ARGS = [
# // https://issues.chromium.org/41491762
'--unsafely-disable-devtools-self-xss-warnings',
'--enable-features=NetworkService,NetworkServiceInProcess',
+ '--enable-network-information-downlink-max',
# added by us:
'--test-type=gpu',
'--disable-sync',
@@ -618,14 +620,21 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
return self
def get_args(self) -> list[str]:
+ if isinstance(self.ignore_default_args, list):
+ default_args = set(CHROME_DEFAULT_ARGS) - set(self.ignore_default_args)
+ elif self.ignore_default_args is True:
+ default_args = []
+ elif not self.ignore_default_args:
+ default_args = CHROME_DEFAULT_ARGS
+
return BrowserLaunchArgs.args_as_list( # convert back to ['--arg=value', '--arg', '--arg=value', ...]
BrowserLaunchArgs.args_as_dict( # uniquify via dict {'arg': 'value', 'arg2': 'value2', ...}
[
- *(CHROME_DEFAULT_ARGS if self.ignore_default_args is not True else []),
+ *default_args,
*self.args,
f'--profile-directory={self.profile_directory}',
*(CHROME_DOCKER_ARGS if IN_DOCKER else []),
- # *(CHROME_HEADLESS_ARGS if self.headless else []),
+ *(CHROME_HEADLESS_ARGS if self.headless else []),
*(CHROME_DISABLE_SECURITY_ARGS if self.disable_security else []),
*(CHROME_DETERMINISTIC_RENDERING_ARGS if self.deterministic_rendering else []),
*(
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index cead570d9..7e0865b1a 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -19,7 +19,7 @@ from playwright.async_api import BrowserContext as PlaywrightBrowserContext
from playwright.async_api import ElementHandle, FrameLocator, Page, Playwright, async_playwright
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validator
-from browser_use.browser.types import BrowserProfile
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.views import (
BrowserError,
BrowserStateSummary,
@@ -342,10 +342,34 @@ class BrowserSession(BaseModel):
# search for potentially conflicting local processes running on the same user_data_dir
for proc in psutil.process_iter(['pid', 'cmdline']):
- if str(self.browser_profile.user_data_dir) in ' '.join(proc.info['cmdline'] or []):
+ if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
+ # suffix_num = str(self.browser_profile.user_data_dir).rsplit('.', 1)[-1] or '1'
+ # suffix_num = int(suffix_num) if suffix_num.isdigit() else 1
+
+ # dir_name = self.browser_profile.user_data_dir.name
+ # incremented_name = dir_name.replace(f'.{suffix_num}', f'.{suffix_num + 1}')
+ # fork_path = self.browser_profile.user_data_dir.parent / incremented_name
+
+ # # keep incrementing the suffix_num until we find a path that doesn't exist
+ # while fork_path.exists():
+ # suffix_num += 1
+ # fork_path = self.browser_profile.user_data_dir.parent / (
+ # dir_name.rsplit('.', 1)[0] + f'.{suffix_num}'
+ # )
+
logger.warning(
f'🚨 Found potentially conflicting Chrome process pid={proc.info["pid"]} already running with the same user_data_dir={self.browser_profile.user_data_dir}'
)
+ # use shutil to recursively copy the user_data_dir to a new location
+ # shutil.copytree(
+ # str(self.browser_profile.user_data_dir),
+ # str(fork_path),
+ # symlinks=True,
+ # ignore_dangling_symlinks=True,
+ # dirs_exist_ok=False,
+ # )
+ # self.browser_profile.user_data_dir = fork_path
+ # self.browser_profile.prepare_user_data_dir()
break
# if a user_data_dir is provided, launch a persistent context with that user_data_dir
diff --git a/examples/browser/stealth.py b/examples/browser/stealth.py
index d1c6ae311..970adaa3e 100644
--- a/examples/browser/stealth.py
+++ b/examples/browser/stealth.py
@@ -1,6 +1,8 @@
import asyncio
import os
+import shutil
import sys
+from pathlib import Path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -8,71 +10,98 @@ from dotenv import load_dotenv
load_dotenv()
+from imgcat import imgcat
from langchain_openai import ChatOpenAI
+from patchright.async_api import async_playwright as async_patchright
+from playwright.async_api import async_playwright
-from browser_use import Agent
-from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser import BrowserSession
llm = ChatOpenAI(model='gpt-4o')
-browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=False,
- disable_security=False,
- keep_alive=True,
- user_data_dir='~/.config/browseruse/profiles/default',
- )
-)
+
+terminal_width, terminal_height = shutil.get_terminal_size((80, 20))
async def main():
- agent = Agent(
- task="""
- Go to https://bot-detector.rebrowser.net/ and verify that all the bot checks are passed.
- """,
- llm=llm,
- browser_session=browser_session,
- )
- await agent.run()
- input('Press Enter to continue to the next test...')
-
- agent = Agent(
- task="""
- Go to https://www.webflow.com/ and verify that the page is not blocked by a bot check.
- """,
- llm=llm,
- browser_session=browser_session,
- )
- await agent.run()
- input('Press Enter to continue to the next test...')
-
- agent = Agent(
- task="""
- Go to https://www.okta.com/ and verify that the page is not blocked by a bot check.
- """,
- llm=llm,
- browser_session=browser_session,
- )
- await agent.run()
-
- agent = Agent(
- task="""
- Go to https://abrahamjuliot.github.io/creepjs/ and verify that the detection score is >50%.
- """,
- llm=llm,
- browser_session=browser_session,
+ browser_session = BrowserSession(
+ playwright=await async_playwright().start(),
+ headless=False,
+ disable_security=True,
+ user_data_dir=None,
+ deterministic_rendering=True,
)
- await agent.run()
-
- input('Press Enter to close the browser...')
- agent = Agent(
- task="""
- Go to https://nowsecure.nl/ check the "I'm not a robot" checkbox.
- """,
- llm=llm,
- browser_session=browser_session,
+ stealth_browser_session = BrowserSession(
+ # cdp_url='wss://browser.zenrows.com?apikey=your-api-key-here&proxy_region=na',
+ # or try anchor browser, browserless, steel.dev, browserbase, oxylabs, brightdata, etc.
+ playwright=await async_patchright().start(),
+ headless=False,
+ disable_security=False,
+ user_data_dir='~/.config/browseruse/profiles/stealth',
+ deterministic_rendering=False,
)
- await agent.run()
+ await browser_session.start()
+ await stealth_browser_session.start()
+ await browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
+ await stealth_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
+ await asyncio.sleep(5)
+ await (await browser_session.get_current_page()).screenshot(path='normal_browser.png')
+ print('NORMAL BROWSER:')
+ imgcat(Path('normal_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
+ print()
+ print()
+
+ print('STEALTH BROWSER:')
+ await (await stealth_browser_session.get_current_page()).screenshot(path='stealth_browser.png')
+ imgcat(Path('stealth_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
+ # agent = Agent(
+ # task="""
+ # Go to https://abrahamjuliot.github.io/creepjs/ and verify that the detection score is >50%.
+ # """,
+ # llm=llm,
+ # browser_session=browser_session,
+ # )
+ # await agent.run()
+
+ # input('Press Enter to close the browser...')
+
+ # agent = Agent(
+ # task="""
+ # Go to https://bot-detector.rebrowser.net/ and verify that all the bot checks are passed.
+ # """,
+ # llm=llm,
+ # browser_session=browser_session,
+ # )
+ # await agent.run()
+ # input('Press Enter to continue to the next test...')
+
+ # agent = Agent(
+ # task="""
+ # Go to https://www.webflow.com/ and verify that the page is not blocked by a bot check.
+ # """,
+ # llm=llm,
+ # browser_session=browser_session,
+ # )
+ # await agent.run()
+ # input('Press Enter to continue to the next test...')
+
+ # agent = Agent(
+ # task="""
+ # Go to https://www.okta.com/ and verify that the page is not blocked by a bot check.
+ # """,
+ # llm=llm,
+ # browser_session=browser_session,
+ # )
+ # await agent.run()
+
+ # agent = Agent(
+ # task="""
+ # Go to https://nowsecure.nl/ check the "I'm not a robot" checkbox.
+ # """,
+ # llm=llm,
+ # browser_session=browser_session,
+ # )
+ # await agent.run()
input('Press Enter to close the browser...')
diff --git a/pyproject.toml b/pyproject.toml
index fb62fc6d9..81cdd1aa5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -62,6 +62,7 @@ cli = [
examples = [
# botocore: only needed for Bedrock Claude boto3 examples/models/bedrock_claude.py
"botocore>=1.37.23",
+ "imgcat>=0.6.0",
]
all = [
"browser-use[memory,cli,examples]",
diff --git a/tests/test_browser_config_models.py b/tests/test_browser_config_models.py
index 4828d70c6..02d2279bd 100644
--- a/tests/test_browser_config_models.py
+++ b/tests/test_browser_config_models.py
@@ -2,8 +2,8 @@ import os
import pytest
+from browser_use.browser.profile import BrowserProfile, ProxySettings
from browser_use.browser.session import BrowserSession
-from browser_use.browser.types import BrowserProfile, ProxySettings
@pytest.mark.asyncio
diff --git a/tests/test_tab_management.py b/tests/test_tab_management.py
index e4c421251..1f40f41d0 100644
--- a/tests/test_tab_management.py
+++ b/tests/test_tab_management.py
@@ -8,8 +8,8 @@ from pytest_httpserver import HTTPServer
load_dotenv()
from browser_use.agent.views import ActionModel
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
-from browser_use.browser.types import BrowserProfile
from browser_use.controller.service import Controller
# Set up test logging