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
ruff
Sandeep Salwane0565496e872
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.pyindex fb3d31578..d79fcd3f1 100644--- a/browser_use/browser/browser.py+++ b/browser_use/browser/browser.py@@ -27,7 +27,7 @@ from browser_use.browser.chrome import (CHROME_HEADLESS_ARGS,)from browser_use.browser.context import BrowserContext, BrowserContextConfig-from browser_use.browser.utils.screen_resolution import get_window_adjustments, get_screen_resolution+from browser_use.browser.utils.screen_resolution import get_screen_resolution, get_window_adjustmentsfrom browser_use.utils import time_execution_asynclogger = logging.getLogger(__name__)@@ -299,22 +299,13 @@ class Browser:],}- # Add viewport size to launch options for non-headless mode- viewport = None- if (- not self.config.headless- and hasattr(self.config, 'new_context_config')- and hasattr(self.config.new_context_config, 'browser_window_size')- ):- viewport = self.config.new_context_config.browser_window_size.model_dump()-browser = await browser_class.launch(headless=self.config.headless,channel='chrome',args=args[self.config.browser_class],proxy=self.config.proxy.model_dump() if self.config.proxy else None,handle_sigterm=False,- handle_sigint=False,+ handle_sigint=False)return browser@@ -400,4 +391,4 @@ class Browser:try:await client.aclose()except Exception as e:- logger.debug(f'Error closing httpx client: {e}')\ No newline at end of file+ logger.debug(f'Error closing httpx client: {e}')diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 01832690b..ef6769c68 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -44,7 +44,30 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)# Constants-BROWSER_CHROME_HEIGHT = 85 # Height adjustment for browser chrome (title bar, tabs, etc.)+# Default height adjustment for browser chrome (title bar, tabs, etc.)+# This can vary by platform, browser, and display settings+BROWSER_CHROME_HEIGHT_DEFAULT = 85+BROWSER_CHROME_HEIGHT_WINDOWS = 85+BROWSER_CHROME_HEIGHT_MACOS = 80+BROWSER_CHROME_HEIGHT_LINUX = 90++def get_browser_chrome_height() -> int:+ """Determine appropriate browser chrome height based on platform"""+ import platform+ system = platform.system().lower()++ if system == 'darwin':+ return BROWSER_CHROME_HEIGHT_MACOS+ elif system == 'windows':+ return BROWSER_CHROME_HEIGHT_WINDOWS+ elif system == 'linux':+ return BROWSER_CHROME_HEIGHT_LINUX+ else:+ return BROWSER_CHROME_HEIGHT_DEFAULT++# Get the appropriate chrome height for current platform+BROWSER_CHROME_HEIGHT = get_browser_chrome_height()+class BrowserContextWindowSize(BaseModel):"""Window size configuration for browser context"""@@ -1747,12 +1770,18 @@ class BrowserContext:# Fallback to using JavaScripttry:- await page.evaluate(f"""- () => {{- window.resizeTo({window_size['width']}, {window_size['height'] + BROWSER_CHROME_HEIGHT});- }}- """)- logger.debug(f'Used JavaScript to set window size to {window_size["width"]}x{window_size["height"] + BROWSER_CHROME_HEIGHT}')+ await page.evaluate(+ """+ (width, height) => {+ window.resizeTo(width, height);+ }+ """,+ window_size['width'],+ window_size['height'] + BROWSER_CHROME_HEIGHT+ )+ logger.debug(+ f'Used JavaScript to set window size to {window_size["width"]}x{window_size["height"] + BROWSER_CHROME_HEIGHT}'+ )except Exception as e:logger.debug(f'JavaScript window resize failed: {e}')@@ -1773,4 +1802,4 @@ class BrowserContext:TimeoutError: If the element does not become visible within the specified timeout."""page = await self.get_current_page()- await page.wait_for_selector(selector, state='visible', timeout=timeout)\ No newline at end of file+ await page.wait_for_selector(selector, state='visible', timeout=timeout)diff --git a/examples/browserDemo.py b/examples/browserDemo.pyindex 16087c1fc..79e30e12f 100644--- a/examples/browserDemo.py+++ b/examples/browserDemo.py@@ -4,6 +4,9 @@ This script shows how to set a custom window size for the browser."""import asyncio+import sys+from typing import Any, Dict+from browser_use.browser.browser import Browser, BrowserConfigfrom browser_use.browser.context import BrowserContextConfig, BrowserContextWindowSize@@ -14,45 +17,92 @@ async def main():window_size = BrowserContextWindowSize(width=800, height=400) # Small size to clearly demonstrate the fixconfig = BrowserContextConfig(browser_window_size=window_size)- browser = Browser(- config=BrowserConfig(- headless=False, # Use non-headless mode to see the window- )- )-+ browser = None+ browser_context = None+try:+ # Initialize the browser with error handling+ try:+ browser = Browser(+ config=BrowserConfig(+ headless=False, # Use non-headless mode to see the window+ )+ )+ except Exception as e:+ print(f"Failed to initialize browser: {e}")+ return 1+# Create a browser context- browser_context = await browser.new_context(config=config)+ try:+ browser_context = await browser.new_context(config=config)+ except Exception as e:+ print(f"Failed to create browser context: {e}")+ return 1# Get the current pagepage = await browser_context.get_current_page()- # Navigate to a test page- await page.goto('https://example.com')+ # Navigate to a test page with error handling+ try:+ await page.goto('https://example.com')+ await page.wait_for_load_state('domcontentloaded')+ except Exception as e:+ print(f"Failed to navigate to example.com: {e}")+ print("Continuing with test anyway...")# Wait a bit to see the windowawait asyncio.sleep(2)# Get the actual viewport size using JavaScriptviewport_size = await page.evaluate("""- () => {- return {- width: window.innerWidth,- height: window.innerHeight- }- }- """)+ () => {+ return {+ width: window.innerWidth,+ height: window.innerHeight+ }+ }+ """)print(f'Configured window size: {window_size.model_dump()}')print(f'Actual viewport size: {viewport_size}')++ # Validate the window size+ validate_window_size(window_size.model_dump(), viewport_size)# Wait a bit more to see the windowawait asyncio.sleep(3)++ return 0+ except Exception as e:+ print(f"Unexpected error: {e}")+ return 1+finally:- # Close the browser- await browser.close()+ # Close resources+ if browser_context:+ await browser_context.close()+ if browser:+ await browser.close()+++def validate_window_size(configured: Dict[str, Any], actual: Dict[str, Any]) -> None:+ """Compare configured window size with actual size and report differences"""+ # 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("WARNING: Significant difference between configured and actual window size!")+ print(f"Width difference: {width_diff}px, Height difference: {height_diff}px")+ else:+ print("Window size validation passed: actual size matches configured size within tolerance")if __name__ == '__main__':- asyncio.run(main())\ No newline at end of file+ result = asyncio.run(main())+ sys.exit(result)