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
feat: add Browser.from_system_chrome() for real browser auto-detection - auto-detects chrome executable and user data dir on macos/windows/linux - auto-selects first available profile if none specified - added Browser.list_chrome_profiles() to see available profiles - updated examples to prompt user for profile selection - fixed missing browser.stop() in save_cookies.py
Laith Weinberger77160b7d79e5
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 7977cf517..0b01c1c11 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -379,6 +379,57 @@ class BrowserSession(BaseModel):# Cache of original viewport size for coordinate conversion (set when browser state is captured)_original_viewport_size: tuple[int, int] | None = PrivateAttr(default=None)+ @classmethod+ def from_system_chrome(cls, profile_directory: str | None = None, **kwargs: Any) -> Self:+ """Create a BrowserSession using system's Chrome installation and profile"""+ from browser_use.skill_cli.utils import find_chrome_executable, get_chrome_profile_path, list_chrome_profiles++ executable_path = find_chrome_executable()+ if executable_path is None:+ raise RuntimeError(+ 'Chrome not found. Please install Chrome or use Browser() with explicit executable_path.\n'+ 'Expected locations:\n'+ ' macOS: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome\n'+ ' Linux: /usr/bin/google-chrome or /usr/bin/chromium\n'+ ' Windows: C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'+ )++ user_data_dir = get_chrome_profile_path(None)+ if user_data_dir is None:+ raise RuntimeError(+ 'Could not detect Chrome profile directory for your platform.\n'+ 'Expected locations:\n'+ ' macOS: ~/Library/Application Support/Google/Chrome\n'+ ' Linux: ~/.config/google-chrome\n'+ ' Windows: %LocalAppData%\\Google\\Chrome\\User Data'+ )++ # Auto-select profile if not specified+ profiles = list_chrome_profiles()+ if profile_directory is None:+ if profiles:+ # Use first available profile+ profile_directory = profiles[0]['directory']+ logging.getLogger('browser_use').info(+ f"Auto-selected Chrome profile: {profiles[0]['name']} ({profile_directory})"+ )+ else:+ profile_directory = 'Default'++ return cls(+ executable_path=executable_path,+ user_data_dir=user_data_dir,+ profile_directory=profile_directory,+ **kwargs,+ )++ @classmethod+ def list_chrome_profiles(cls) -> list[dict[str, str]]:+ """List available Chrome profiles on the system"""+ from browser_use.skill_cli.utils import list_chrome_profiles++ return list_chrome_profiles()+# Convenience properties for common browser settings@propertydef cdp_url(self) -> str | None:diff --git a/browser_use/skill_cli/utils.py b/browser_use/skill_cli/utils.pyindex bfc45ba64..473e66d4e 100644--- a/browser_use/skill_cli/utils.py+++ b/browser_use/skill_cli/utils.py@@ -139,6 +139,39 @@ def get_chrome_profile_path(profile: str | None) -> str | None:return None+def list_chrome_profiles() -> list[dict[str, str]]:+ """List available Chrome profiles with their names.++ Returns:+ List of dicts with 'directory' and 'name' keys, ex:+ [{'directory': 'Default', 'name': 'Person 1'}, {'directory': 'Profile 1', 'name': 'Work'}]+ """+ import json++ user_data_dir = get_chrome_profile_path(None)+ if user_data_dir is None:+ return []++ local_state_path = Path(user_data_dir) / 'Local State'+ if not local_state_path.exists():+ return []++ try:+ with open(local_state_path) as f:+ local_state = json.load(f)++ info_cache = local_state.get('profile', {}).get('info_cache', {})+ profiles = []+ for directory, info in info_cache.items():+ profiles.append({+ 'directory': directory,+ 'name': info.get('name', directory),+ })+ return sorted(profiles, key=lambda p: p['directory'])+ except (json.JSONDecodeError, KeyError, OSError):+ return []++def get_config_dir() -> Path:"""Get browser-use config directory."""if sys.platform == 'win32':diff --git a/docs/customize/browser/all-parameters.mdx b/docs/customize/browser/all-parameters.mdxindex 27fd82986..113b120bb 100644--- a/docs/customize/browser/all-parameters.mdx+++ b/docs/customize/browser/all-parameters.mdx@@ -133,3 +133,59 @@ browser = Browser(browser_profile=profile)`Browser` is an alias for `BrowserSession` - they are exactly the same class:Use `Browser` for cleaner, more intuitive code.++---++## Class Methods++### `Browser.from_system_chrome()`++Creates a Browser instance using your system's Chrome installation and profile. Automatically detects Chrome executable and user data directory for your platform.++```python+from browser_use import Browser++# Auto-select first available profile+browser = Browser.from_system_chrome()++# Or specify a profile+browser = Browser.from_system_chrome(profile_directory='Profile 1')+```++**Parameters:**+- `profile_directory` (default: `None`): Chrome profile to use (`'Default'`, `'Profile 1'`, etc.). If `None`, auto-selects the first available profile.+- `**kwargs`: Additional arguments passed to `Browser()` constructor (e.g., `headless=False`)++**Returns:** `Browser` instance configured to use your system Chrome++**Raises:** `RuntimeError` if Chrome is not found on your system++**Note:** You may need to fully close Chrome before using this, so Chrome profiles aren't used by multiple instances simultaneously.++---++### `Browser.list_chrome_profiles()`++Lists available Chrome profiles on the system.++```python+from browser_use import Browser++profiles = Browser.list_chrome_profiles()+for p in profiles:+ print(f"{p['directory']}: {p['name']}")+# Output:+# Profile 1: Work+# Profile 5: Personal+```++**Returns:** List of dicts with `'directory'` and `'name'` keys++**Example return value:**+```python+[+ {'directory': 'Default', 'name': 'Person 1'},+ {'directory': 'Profile 1', 'name': 'Work'},+ {'directory': 'Profile 5', 'name': 'Personal'}+]+```diff --git a/docs/customize/browser/real-browser.mdx b/docs/customize/browser/real-browser.mdxindex 4529c8e7f..db891f935 100644--- a/docs/customize/browser/real-browser.mdx+++ b/docs/customize/browser/real-browser.mdx@@ -1,10 +1,13 @@---title: "Real Browser"-description: ""+description: "Connect your existing Chrome browser to preserve authentication"icon: "arrow-right-to-bracket"---+This allows you to automate your existing Chrome browser, so you're already logged into your websites.-Connect your existing Chrome browser to preserve authentication.+<Warning>+You may need to fully close Chrome before running these examples. Additionally, if Google search blocks automated browsers, use DuckDuckGo or other search engines instead.+</Warning>## Basic Example@@ -12,49 +15,62 @@ Connect your existing Chrome browser to preserve authentication.import asynciofrom browser_use import Agent, Browser, ChatOpenAI-# Connect to your existing Chrome browser-browser = Browser(- executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- user_data_dir='~/Library/Application Support/Google/Chrome',- profile_directory='Default',-)+# Auto-selects first available Chrome profile+browser = Browser.from_system_chrome()agent = Agent(task='Visit https://duckduckgo.com and search for "browser-use founders"',browser=browser,llm=ChatOpenAI(model='gpt-4.1-mini'),)+async def main():- await agent.run()+ await agent.run()if __name__ == "__main__":asyncio.run(main())```-> **Note:** You need to fully close chrome before running this example. Also, Google blocks this approach currently so we use DuckDuckGo instead.-+## Choosing a Profile+Chrome supports multiple profiles. List and select the one you want:-## How it Works+```python+from browser_use import Browser++# List available profiles+profiles = Browser.list_chrome_profiles()+for p in profiles:+ print(f"{p['directory']}: {p['name']}")+# Output:+# Profile 1: Work+# Profile 5: Personal++# Use a specific profile+browser = Browser.from_system_chrome(profile_directory='Profile 5')+```-1. **`executable_path`** - Path to your Chrome installation-2. **`user_data_dir`** - Your Chrome profile folder (keeps cookies, extensions, bookmarks)-3. **`profile_directory`** - Specific profile name (Default, Profile 1, etc.)+## Manual Path Configuration-## Platform Paths+If auto-detection doesn't work, specify paths manually:```python-# macOS-executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'-user_data_dir='~/Library/Application Support/Google/Chrome'+browser = Browser(+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ user_data_dir='~/Library/Application Support/Google/Chrome',+ profile_directory='Default',+)+```-# Windows-executable_path='C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'-user_data_dir='%LOCALAPPDATA%\\Google\\Chrome\\User Data'-# Linux-executable_path='/usr/bin/google-chrome'-user_data_dir='~/.config/google-chrome'-```+## How it Works++`Browser.from_system_chrome()` automatically detects:++| Platform | Executable Path | User Data Directory |+|----------|-----------------|---------------------|+| macOS | `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome` | `~/Library/Application Support/Google/Chrome` |+| Windows | `C:\Program Files\Google\Chrome\Application\chrome.exe` | `%LocalAppData%\Google\Chrome\User Data` |+| Linux | `/usr/bin/google-chrome` or `/usr/bin/chromium` | `~/.config/google-chrome` |diff --git a/examples/browser/real_browser.py b/examples/browser/real_browser.pyindex 0342204f0..a4d4769d5 100644--- a/examples/browser/real_browser.py+++ b/examples/browser/real_browser.py@@ -1,3 +1,7 @@+"""+Connect to your existing Chrome browser so it's logged into your websites+"""+import asyncioimport osimport sys@@ -10,20 +14,30 @@ load_dotenv()from browser_use import Agent, Browser, ChatGoogle-# Connect to your existing Chrome browser-browser = Browser(- executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- user_data_dir='~/Library/Application Support/Google/Chrome',- profile_directory='Default',-)++def select_chrome_profile() -> str | None:+ """Prompt user to select a Chrome profile."""+ profiles = Browser.list_chrome_profiles()+ if not profiles:+ return None++ print('Available Chrome profiles:')+ for i, p in enumerate(profiles, 1):+ print(f" {i}. {p['name']}")++ while True:+ choice = input(f'\nSelect profile (1-{len(profiles)}): ').strip()+ if choice.isdigit() and 1 <= int(choice) <= len(profiles):+ return profiles[int(choice) - 1]['directory']+ print('Invalid choice, try again.')-# NOTE: You have to close all Chrome browsers before running this example so that we can launch chrome in debug mode.async def main():- # save storage state+ profile = select_chrome_profile()+ browser = Browser.from_system_chrome(profile_directory=profile)+agent = Agent(llm=ChatGoogle(model='gemini-flash-latest'),- # Google blocks this approach, so we use a different search enginetask='go to amazon.com and search for pens to draw on whiteboards',browser=browser,)diff --git a/examples/browser/save_cookies.py b/examples/browser/save_cookies.pyindex eef6565f5..abc88fd67 100644--- a/examples/browser/save_cookies.py+++ b/examples/browser/save_cookies.py@@ -1,3 +1,10 @@+"""+Export cookies and storage state from your real Chrome browser++This allows you to save your authenticated sessions for later use+without needing to connect to the Chrome profile every time+"""+import asyncioimport osimport sys@@ -10,17 +17,32 @@ load_dotenv()from browser_use import Browser-# Connect to your existing Chrome browser-browser = Browser(- executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- user_data_dir='~/Library/Application Support/Google/Chrome',- profile_directory='Default',-)++def select_chrome_profile() -> str | None:+ """Prompt user to select a Chrome profile."""+ profiles = Browser.list_chrome_profiles()+ if not profiles:+ return None++ print('Available Chrome profiles:')+ for i, p in enumerate(profiles, 1):+ print(f" {i}. {p['name']}")++ while True:+ choice = input(f'\nSelect profile (1-{len(profiles)}): ').strip()+ if choice.isdigit() and 1 <= int(choice) <= len(profiles):+ return profiles[int(choice) - 1]['directory']+ print('Invalid choice, try again.')async def main():+ profile = select_chrome_profile()+ browser = Browser.from_system_chrome(profile_directory=profile)+await browser.start()- await browser.export_storage_state('storage_state3.json')+ await browser.export_storage_state('storage_state.json')+ await browser.stop()+ print('Storage state exported to storage_state.json')if __name__ == '__main__':