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
rename session.py profile.py, fix stealth example, fix tests
Nick Sweeting2f002b4c22f0
diff --git a/browser_use/__init__.py b/browser_use/__init__.pyindex 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 SystemPromptfrom browser_use.agent.service import Agentfrom 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, BrowserSessionfrom browser_use.controller.service import Controllerfrom browser_use.dom.service import DomServicediff --git a/browser_use/browser/__init__.py b/browser_use/browser/__init__.pyindex 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 BrowserProfilefrom .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.pyindex 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 BrowserProfilefrom browser_use.browser.session import BrowserSession-from browser_use.browser.types import BrowserProfileBrowserConfig = BrowserProfileBrowserContextConfig = BrowserProfilediff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 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 BrowserProfilefrom browser_use.browser.session import BrowserSession-from browser_use.browser.types import BrowserProfileBrowser = BrowserSessionBrowserConfig = BrowserProfilediff --git a/browser_use/browser/types.py b/browser_use/browser/profile.pysimilarity index 98%rename from browser_use/browser/types.pyrename to browser_use/browser/profile.pyindex 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, Broreturn selfdef 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.pyindex 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 PlaywrightBrowserContextfrom playwright.async_api import ElementHandle, FrameLocator, Page, Playwright, async_playwrightfrom pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validator-from browser_use.browser.types import BrowserProfile+from browser_use.browser.profile import BrowserProfilefrom 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_dirfor 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_dirdiff --git a/examples/browser/stealth.py b/examples/browser/stealth.pyindex d1c6ae311..970adaa3e 100644--- a/examples/browser/stealth.py+++ b/examples/browser/stealth.py@@ -1,6 +1,8 @@import asyncioimport os+import shutilimport sys+from pathlib import Pathsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))@@ -8,71 +10,98 @@ from dotenv import load_dotenvload_dotenv()+from imgcat import imgcatfrom 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 BrowserSessionllm = 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.tomlindex 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.pyindex 4828d70c6..02d2279bd 100644--- a/tests/test_browser_config_models.py+++ b/tests/test_browser_config_models.py@@ -2,8 +2,8 @@ import osimport pytest+from browser_use.browser.profile import BrowserProfile, ProxySettingsfrom browser_use.browser.session import BrowserSession-from browser_use.browser.types import BrowserProfile, ProxySettings@pytest.mark.asynciodiff --git a/tests/test_tab_management.py b/tests/test_tab_management.pyindex e4c421251..1f40f41d0 100644--- a/tests/test_tab_management.py+++ b/tests/test_tab_management.py@@ -8,8 +8,8 @@ from pytest_httpserver import HTTPServerload_dotenv()from browser_use.agent.views import ActionModel+from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.session import BrowserSession-from browser_use.browser.types import BrowserProfilefrom browser_use.controller.service import Controller# Set up test logging