Skip to content

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

Remove browser examples

Magnus Müller4f5932b5a8a2
diff --git a/examples/browser/multiple_agents_same_browser.py b/examples/browser/multiple_agents_same_browser.py
deleted file mode 100644
index 354c292cf..000000000
--- a/examples/browser/multiple_agents_same_browser.py
+++ /dev/null
@@ -1,49 +0,0 @@
-import asyncio
-import os
-import sys
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
-
-from dotenv import load_dotenv
-
-load_dotenv()
-
-
-from browser_use import Agent
-from browser_use.browser.profile import BrowserProfile
-from browser_use.browser.session import BrowserSession
-from browser_use.llm import ChatOpenAI
-
-
-async def main():
- browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- keep_alive=True,
- user_data_dir=None,
- headless=False,
- )
- )
- await browser_session.start()
-
- current_agent = None
- llm = ChatOpenAI(model='gpt-4.1')
-
- task1 = 'find todays weather on San Francisco and extract it as json'
- task2 = 'find todays weather in Zurich and extract it as json'
-
- agent1 = Agent(
- task=task1,
- browser_session=browser_session,
- llm=llm,
- )
- agent2 = Agent(
- task=task2,
- browser_session=browser_session,
- llm=llm,
- )
-
- await asyncio.gather(agent1.run(), agent2.run())
- await browser_session.kill()
-
-
-asyncio.run(main())
diff --git a/examples/browser/stealth.py b/examples/browser/stealth.py
deleted file mode 100644
index d131aba36..000000000
--- a/examples/browser/stealth.py
+++ /dev/null
@@ -1,205 +0,0 @@
-# pyright: reportMissingImports=false
-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__)))))
-
-from dotenv import load_dotenv
-
-load_dotenv()
-
-from imgcat import imgcat
-
-from browser_use.browser import BrowserSession
-from browser_use.browser.events import NavigateToUrlEvent
-from browser_use.browser.profile import BrowserProfile
-from browser_use.llm import ChatOpenAI
-
-llm = ChatOpenAI(model='gpt-4.1')
-
-terminal_width, terminal_height = shutil.get_terminal_size((80, 20))
-
-
-async def take_screenshot_cdp(browser_session: BrowserSession, filename: str):
- """Take a screenshot using CDP."""
- # Get current CDP session
- cdp_session = await browser_session.get_or_create_cdp_session()
-
- # Take screenshot using CDP
- result = await cdp_session.cdp_client.send.Page.captureScreenshot(params={'format': 'png'}, session_id=cdp_session.session_id)
-
- # Save the screenshot
- import base64
-
- screenshot_data = base64.b64decode(result['data'])
- Path(filename).write_bytes(screenshot_data)
-
-
-async def main():
- # Note: Patchright is deprecated, using standard stealth mode
-
- print('\n\nNORMAL BROWSER:')
- # Default Playwright Chromium Browser
- normal_browser_session = BrowserSession(
- # executable_path=<defaults to playwright builtin browser stored in ms-cache directory>,
- browser_profile=BrowserProfile(
- user_data_dir=None,
- headless=False,
- stealth=False,
- # deterministic_rendering=False,
- # disable_security=False,
- )
- )
- await normal_browser_session.start()
-
- # Navigate using events
- nav_event = normal_browser_session.event_bus.dispatch(
- NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
- )
- await nav_event
- await asyncio.sleep(5)
-
- # Take screenshot using CDP
- await take_screenshot_cdp(normal_browser_session, 'normal_browser.png')
- imgcat(Path('normal_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
- await normal_browser_session.kill()
-
- print('\n\nSTEALTH BROWSER:')
- 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.
- browser_profile=BrowserProfile(
- user_data_dir='~/.config/browseruse/profiles/stealth',
- stealth=True,
- headless=False,
- disable_security=False,
- deterministic_rendering=False,
- )
- )
- await stealth_browser_session.start()
-
- # Navigate using events
- nav_event = stealth_browser_session.event_bus.dispatch(
- NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
- )
- await nav_event
- await asyncio.sleep(5)
-
- # Take screenshot using CDP
- await take_screenshot_cdp(stealth_browser_session, 'stealth_browser.png')
- imgcat(Path('stealth_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
- await stealth_browser_session.kill()
-
- # Brave Browser
- if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():
- print('\n\nBRAVE BROWSER:')
- brave_browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
- headless=False,
- disable_security=False,
- user_data_dir='~/.config/browseruse/profiles/brave',
- deterministic_rendering=False,
- )
- )
- await brave_browser_session.start()
-
- # Navigate using events
- nav_event = brave_browser_session.event_bus.dispatch(
- NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
- )
- await nav_event
- await asyncio.sleep(5)
-
- # Take screenshot using CDP
- await take_screenshot_cdp(brave_browser_session, 'brave_browser.png')
- imgcat(Path('brave_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
- await brave_browser_session.kill()
-
- if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():
- print('\n\nBRAVE + STEALTH BROWSER:')
- brave_stealth_browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
- headless=False,
- stealth=True, # Enable stealth mode
- disable_security=False,
- user_data_dir=None,
- deterministic_rendering=False,
- ),
- # Device emulation can be done via viewport/user_agent settings
- )
- await brave_stealth_browser_session.start()
-
- # Navigate using events
- nav_event = brave_stealth_browser_session.event_bus.dispatch(
- NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
- )
- await nav_event
- await asyncio.sleep(5)
-
- # Take screenshot using CDP
- await take_screenshot_cdp(brave_stealth_browser_session, 'brave_stealth_browser.png')
- imgcat(Path('brave_stealth_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
-
- input('Press [Enter] to close the browser...')
- await brave_stealth_browser_session.kill()
-
- # print()
- # 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...')
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/browser/using_cdp.py b/examples/browser/using_cdp.py
deleted file mode 100644
index 773c6c3ff..000000000
--- a/examples/browser/using_cdp.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""
-Simple demonstration of the CDP feature.
-
-To test this locally, follow these steps:
-1. Create a shortcut for the executable Chrome file.
-2. Add the following argument to the shortcut:
- - On Windows: `--remote-debugging-port=9222`
-3. Open a web browser and navigate to `http://localhost:9222/json/version` to verify that the Remote Debugging Protocol (CDP) is running.
-4. Launch this example.
-
-@dev You need to set the `GOOGLE_API_KEY` environment variable before proceeding.
-"""
-
-import asyncio
-import os
-import sys
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
-
-from dotenv import load_dotenv
-
-load_dotenv()
-
-
-from browser_use import Agent, Controller
-from browser_use.browser import BrowserProfile, BrowserSession
-from browser_use.llm import ChatGoogle
-
-api_key = os.getenv('GOOGLE_API_KEY')
-if not api_key:
- raise ValueError('GOOGLE_API_KEY is not set')
-
-browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=False,
- ),
- cdp_url='http://localhost:9222',
-)
-controller = Controller()
-
-
-async def main():
- task = 'In docs.google.com write my Papa a quick thank you for everything letter \n - Magnus'
- task += ' and save the document as pdf'
- # Assert api_key is not None to satisfy type checker
- assert api_key is not None, 'GOOGLE_API_KEY must be set'
- model = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)
- agent = Agent(
- task=task,
- llm=model,
- controller=controller,
- browser_session=browser_session,
- )
-
- await agent.run()
- await browser_session.kill()
-
- input('Press Enter to close...')
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/browser/window_sizing.py b/examples/browser/window_sizing.py
deleted file mode 100644
index 077c0e67a..000000000
--- a/examples/browser/window_sizing.py
+++ /dev/null
@@ -1,179 +0,0 @@
-"""
-Examples demonstrating browser window sizing features.
-
-This example shows how to:
-1. Set a custom window size for the browser
-2. Verify the actual viewport dimensions
-3. Use the no_viewport option
-"""
-
-import asyncio
-from typing import Any
-
-from dotenv import load_dotenv
-
-load_dotenv()
-
-from browser_use.browser import BrowserProfile, BrowserSession
-from browser_use.browser.events import NavigateToUrlEvent
-
-
-async def get_viewport_size_cdp(browser_session: BrowserSession) -> dict[str, int]:
- """Get viewport size using CDP."""
- cdp_session = await browser_session.get_or_create_cdp_session()
- result = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': '({width: window.innerWidth, height: window.innerHeight})', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- return result.get('result', {}).get('value', {})
-
-
-async def get_window_size_cdp(browser_session: BrowserSession) -> dict[str, int]:
- """Get window outer size using CDP."""
- cdp_session = await browser_session.get_or_create_cdp_session()
- result = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': '({width: window.outerWidth, height: window.outerHeight})', 'returnByValue': True},
- session_id=cdp_session.session_id,
- )
- return result.get('result', {}).get('value', {})
-
-
-async def example_custom_window_size():
- """Example 1: Setting a custom browser window size"""
- print('\n=== Example 1: Custom Window Size ===')
-
- # Create a browser profile with a specific window size
- profile = BrowserProfile(
- window_size={'width': 800, 'height': 600}, # Small size for demonstration
- # **playwright.devices['iPhone 13'] # or you can use a playwright device profile
- # device_scale_factor=1.0, # change to 2~3 to emulate a high-DPI display for high-res screenshots
- # viewport={'width': 800, 'height': 600}, # set the viewport (aka content size)
- # screen={'width': 800, 'height': 600}, # hardware display size to report to websites via JS
- headless=False, # Use non-headless mode to see the window
- )
-
- browser_session = None
-
- try:
- # Initialize and start the browser session
- browser_session = BrowserSession(
- browser_profile=profile,
- )
- await browser_session.start()
-
- # Navigate to a test page using events
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url='https://example.com'))
- await nav_event
-
- # Wait a bit to see the window
- await asyncio.sleep(1)
-
- # Get the actual viewport size using CDP
- actual_content_size = await get_viewport_size_cdp(browser_session)
-
- if profile.viewport:
- expected_page_size = dict(profile.viewport)
- elif profile.window_size:
- expected_page_size = {
- 'width': profile.window_size['width'],
- 'height': profile.window_size['height'] - 87,
- } # 87px is the height of the navbar, title, rim ish
- else:
- # Default expected size if neither viewport nor window_size is set
- expected_page_size = {'width': 800, 'height': 600}
- _log_size = lambda size: f'{size["width"]}x{size["height"]}px'
- print(f'Expected {_log_size(expected_page_size)} vs actual {_log_size(actual_content_size)}')
-
- # Validate the window size
- validate_window_size(expected_page_size, actual_content_size)
-
- # Wait a bit more to see the window
- await asyncio.sleep(2)
-
- except Exception as e:
- print(f'Error in example 1: {e}')
-
- finally:
- # Close resources
- if browser_session:
- await browser_session.kill()
-
-
-async def example_no_viewport_option():
- """Example 2: Testing browser window sizing with no_viewport option"""
- print('\n=== Example 2: Window Sizing with no_viewport=False ===')
-
- profile = BrowserProfile(window_size={'width': 1440, 'height': 900}, no_viewport=False, headless=False)
-
- browser_session = None
-
- try:
- browser_session = BrowserSession(browser_profile=profile)
- await browser_session.start()
-
- # Navigate using events
- nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url='https://example.com'))
- await nav_event
- await asyncio.sleep(1)
-
- # Get viewport size (inner dimensions) using CDP
- viewport = await get_viewport_size_cdp(browser_session)
- if profile.window_size:
- print(f'Configured size: width={profile.window_size["width"]}, height={profile.window_size["height"]}')
- else:
- print('No window size configured')
- print(f'Actual viewport size: {viewport}')
-
- # Get the actual window size (outer dimensions) using CDP
- window_size = await get_window_size_cdp(browser_session)
- print(f'Actual window size (outer): {window_size}')
-
- await asyncio.sleep(2)
-
- except Exception as e:
- print(f'Error in example 2: {e}')
-
- finally:
- if browser_session:
- await browser_session.kill()
-
-
-def validate_window_size(configured: dict[str, Any], actual: dict[str, Any]) -> None:
- """Compare configured window size with actual size and report differences.
-
- Raises:
- Exception: If the window size difference exceeds tolerance
- """
- # Allow for small differences due to browser chrome, scrollbars, etc.
- width_diff = abs(configured['width'] - actual['width'])
- height_diff = abs(configured['height'] - actual['height'])
-
- # Tolerance of 5% or 20px, whichever is greater
- width_tolerance = max(configured['width'] * 0.05, 20)
- height_tolerance = max(configured['height'] * 0.05, 20)
-
- if width_diff > width_tolerance or height_diff > height_tolerance:
- print(f'⚠️ WARNING: Significant difference between expected and actual page size! ±{width_diff}x{height_diff}px')
- raise Exception('Window size validation failed')
- else:
- print('✅ Window size validation passed: actual size matches configured size within tolerance')
-
- return None
-
-
-async def main():
- """Run all window sizing examples"""
- print('Browser Window Sizing Examples')
- print('==============================')
-
- # Run example 1
- await example_custom_window_size()
-
- # Run example 2
- await example_no_viewport_option()
-
- print('\n✅ All examples completed!')
-
-
-if __name__ == '__main__':
- asyncio.run(main())