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
CamelCase to snake_case
Gregor Žunič942a00c10926
diff --git a/browser_use/actor/README.md b/browser_use/actor/README.mdindex c7bd728bc..7814c17f9 100644--- a/browser_use/actor/README.md+++ b/browser_use/actor/README.md@@ -19,36 +19,36 @@ from browser_use import Browser# Create and start browser sessionbrowser = Browser()-await browser.start()`+await browser.start()# Use integrated browser methods directly-target = await browser.newTarget("https://example.com")-targets = await browser.getTargets()+target = await browser.new_target("https://example.com")+targets = await browser.get_targets()current_target = await browser.get_current_target()``````python# Get targets (multiple ways) - using browser methods-target = await browser.newTarget() # Create blank tab-target = await browser.newTarget("https://example.com") # Create tab with URL-targets = await browser.getTargets() # Get all existing tabs+target = await browser.new_target() # Create blank tab+target = await browser.new_target("https://example.com") # Create tab with URL+targets = await browser.get_targets() # Get all existing tabs# Navigate target to URLawait target.goto("https://example.com")-await browser.closeTarget(target)+await browser.close_target(target)``````python# Find elements by CSS selector-elements = await target.getElementsByCSSSelector("input[type='text']")-buttons = await target.getElementsByCSSSelector("button.submit")+elements = await target.get_elements_by_css_selector("input[type='text']")+buttons = await target.get_elements_by_css_selector("button.submit")# Get element by backend node ID-element = await target.getElement(backend_node_id=12345)+element = await target.get_element(backend_node_id=12345)```-Unlike other libraries, the native implementation for `getElementsByCSSSelector` does not support waiting for the element to be visible.+Unlike other libraries, the native implementation for `get_elements_by_css_selector` does not support waiting for the element to be visible.```python# Element actions@@ -57,12 +57,12 @@ await element.fill("Hello World")await element.hover()await element.focus()await element.check()-await element.selectOption(["option1", "option2"])+await element.select_option(["option1", "option2"])# Element properties-value = await element.getAttribute("value")-box = await element.getBoundingBox()-info = await element.getBasicInfo()+value = await element.get_attribute("value")+box = await element.get_bounding_box()+info = await element.get_basic_info()``````python@@ -78,7 +78,7 @@ mouse = await target.mouseawait mouse.scroll(x=0, y=100, delta_y=-500) # x,y (coordinates to scroll on), delta_y (how much to scroll)await target.press("Control+A") # Key combinations supportedawait target.press("Escape")-await target.setViewportSize(width=1920, height=1080)+await target.set_viewport_size(width=1920, height=1080)await target.reload()page_screenshot = await target.screenshot() # JPEG by defaultpage_png = await target.screenshot(format="png")@@ -92,24 +92,24 @@ page_png = await target.screenshot(format="png")## API Reference### Browser Methods (Browser Operations)-- `newTarget(url=None)` → `Target` - Create blank tab or navigate to URL-- `getTargets()` → `list[Target]` - Get all page/iframe targets-- `closeTarget(target: Target | str)` - Close target by object or ID+- `new_target(url=None)` → `Target` - Create blank tab or navigate to URL+- `get_targets()` → `list[Target]` - Get all page/iframe targets+- `close_target(target: Target | str)` - Close target by object or ID- `cookies(urls=None)` → `list[Cookie]` - Get cookies for specified URLs (or all if None)-- `clearCookies()` - Clear all cookies+- `clear_cookies()` - Clear all cookies- `get_current_target()` → `Target | None` - Get the current target### Target Methods-- `getElementsByCSSSelector(selector: str)` → `list[Element]` - Find elements by CSS selector-- `getElement(backend_node_id: int)` → `Element` - Get element by backend node ID+- `get_elements_by_css_selector(selector: str)` → `list[Element]` - Find elements by CSS selector+- `get_element(backend_node_id: int)` → `Element` - Get element by backend node ID- `goto(url: str)` - Navigate this target to URL-- `goBack()`, `goForward()` - Navigate target history (with proper error handling)+- `go_back()`, `go_forward()` - Navigate target history (with proper error handling)- `evaluate(page_function: str, *args)` → `str` - Execute JavaScript (MUST use (...args) => format) and return string (objects/arrays are JSON-stringified)- `press(key: str)` - Press key on page (supports "Control+A" format)-- `setViewportSize(width: int, height: int)` - Set viewport dimensions+- `set_viewport_size(width: int, height: int)` - Set viewport dimensions- `reload()` - Reload the current page- `screenshot(format='jpeg', quality=None)` → `str` - Take page screenshot and return base64-- `getUrl()` → `str`, `getTitle()` → `str` - Get page info+- `get_url()` → `str`, `get_title()` → `str` - Get page info### Element Methods (Supported Only)- `click(button='left', click_count=1, modifiers=None)` - Click element@@ -117,12 +117,12 @@ page_png = await target.screenshot(format="png")- `hover()` - Hover over element- `focus()` - Focus the element- `check()` - Toggle checkbox/radio button (clicks to change state)-- `selectOption(values: str | list[str])` - Select dropdown options (string or array)-- `dragTo(target: Element | Position, source_position=None, target_position=None)` - Drag to target-- `getAttribute(name: str)` → `str | None` - Get attribute value-- `getBoundingBox()` → `BoundingBox | None` - Get element position/size+- `select_option(values: str | list[str])` - Select dropdown options (string or array)+- `drag_to(target: Element | Position, source_position=None, target_position=None)` - Drag to target+- `get_attribute(name: str)` → `str | None` - Get attribute value+- `get_bounding_box()` → `BoundingBox | None` - Get element position/size- `screenshot(format='jpeg', quality=None)` → `str` - Take element screenshot and return base64-- `getBasicInfo()` → `ElementInfo` - Get comprehensive element information+- `get_basic_info()` → `ElementInfo` - Get comprehensive element information### Mouse Methods@@ -152,13 +152,13 @@ class BoundingBox(TypedDict):### ElementInfo```pythonclass ElementInfo(TypedDict):- backendNodeId: int- nodeId: int | None- nodeName: str- nodeType: int- nodeValue: str | None+ backend_node_id: int+ node_id: int | None+ node_name: str+ node_type: int+ node_value: str | Noneattributes: dict[str, str]- boundingBox: BoundingBox | None+ bounding_box: BoundingBox | None```## Important LLM Usage Notes@@ -172,13 +172,13 @@ class ElementInfo(TypedDict):- **ESCAPING**: Use `\\"` to escape double quotes inside selectors, never mix quote patterns**METHOD RESTRICTIONS:**-- `getElementsByCSSSelector()` returns immediately, no waiting-- For dropdowns: use `element.selectOption("value")` or `element.selectOption(["val1", "val2"])`, not `element.fill()`-- No methods: `element.submit()`, `element.dispatchEvent()`, `element.getProperty()`, `target.querySelectorAll()`+- `get_elements_by_css_selector()` returns immediately, no waiting+- For dropdowns: use `element.select_option("value")` or `element.select_option(["val1", "val2"])`, not `element.fill()`+- No methods: `element.submit()`, `element.dispatch_event()`, `element.get_property()`, `target.query_selector_all()`- Form submission: click submit button or use `target.press("Enter")`-- Get properties: use `target.evaluate("() => element.value")` not `element.getProperty()`+- Get properties: use `target.evaluate("() => element.value")` not `element.get_property()`**ERROR PREVENTION:**-- Loop prevention: verify page state changes with `target.getUrl()`, `target.getTitle()`, `element.getAttribute()`+- Loop prevention: verify page state changes with `target.get_url()`, `target.get_title()`, `element.get_attribute()`- Validate selectors before use: ensure no excessive escaping like `\\\\\\\\`- Test complex selectors: if a selector fails, simplify it step by stepdiff --git a/browser_use/actor/element.py b/browser_use/actor/element.pyindex 272dc7760..9661027ce 100644--- a/browser_use/actor/element.py+++ b/browser_use/actor/element.py@@ -370,7 +370,7 @@ class Element:async def hover(self) -> None:"""Hover over the element."""- box = await self.getBoundingBox()+ box = await self.get_bounding_box()if not box:raise RuntimeError('Element is not visible or has no bounding box')@@ -390,7 +390,7 @@ class Element:"""Check or uncheck a checkbox/radio button."""await self.click()- async def selectOption(self, values: str | list[str]) -> None:+ async def select_option(self, values: str | list[str]) -> None:"""Select option(s) in a select element."""if isinstance(values, str):values = [values]@@ -447,7 +447,7 @@ class Element:option_element = Element(self._browser_session, option_backend_id, self._session_id)await option_element.click()- async def dragTo(+ async def drag_to(self,target: Union['Element', Position],source_position: Position | None = None,@@ -459,7 +459,7 @@ class Element:source_x = source_position['x']source_y = source_position['y']else:- source_box = await self.getBoundingBox()+ source_box = await self.get_bounding_box()if not source_box:raise RuntimeError('Source element is not visible')source_x = source_box['x'] + source_box['width'] / 2@@ -471,13 +471,13 @@ class Element:target_y = target['y']else:if target_position:- target_box = await target.getBoundingBox()+ target_box = await target.get_bounding_box()if not target_box:raise RuntimeError('Target element is not visible')target_x = target_box['x'] + target_position['x']target_y = target_box['y'] + target_position['y']else:- target_box = await target.getBoundingBox()+ target_box = await target.get_bounding_box()if not target_box:raise RuntimeError('Target element is not visible')target_x = target_box['x'] + target_box['width'] / 2@@ -500,7 +500,7 @@ class Element:)# Element properties and queries- async def getAttribute(self, name: str) -> str | None:+ async def get_attribute(self, name: str) -> str | None:"""Get an attribute value."""node_id = await self._get_node_id()params: 'GetAttributesParameters' = {'nodeId': node_id}@@ -512,7 +512,7 @@ class Element:return attributes[i + 1]return None- async def getBoundingBox(self) -> BoundingBox | None:+ async def get_bounding_box(self) -> BoundingBox | None:"""Get the bounding box of the element."""try:node_id = await self._get_node_id()@@ -552,7 +552,7 @@ class Element:Base64-encoded image data"""# Get element's bounding box- box = await self.getBoundingBox()+ box = await self.get_bounding_box()if not box:raise RuntimeError('Element is not visible or has no bounding box')@@ -570,7 +570,7 @@ class Element:return result['data']- async def getBasicInfo(self) -> ElementInfo:+ async def get_basic_info(self) -> ElementInfo:"""Get basic information about the element including coordinates and properties."""try:# Get basic node information@@ -580,7 +580,7 @@ class Element:node_info = describe_result['node']# Get bounding box- bounding_box = await self.getBoundingBox()+ bounding_box = await self.get_bounding_box()# Get attributes as a proper dictattributes_list = node_info.get('attributes', [])diff --git a/browser_use/actor/playground/flights.py b/browser_use/actor/playground/flights.pyindex 9f5b68d25..2a7d95f35 100644--- a/browser_use/actor/playground/flights.py+++ b/browser_use/actor/playground/flights.py@@ -21,10 +21,10 @@ async def main():await asyncio.sleep(2)- round_trip_button = await target.mustGetElementByPrompt('round trip button', llm)+ round_trip_button = await target.must_get_element_by_prompt('round trip button', llm)await round_trip_button.click()- one_way_button = await target.mustGetElementByPrompt('one way button', llm)+ one_way_button = await target.must_get_element_by_prompt('one way button', llm)await one_way_button.click()await asyncio.sleep(0.5)diff --git a/browser_use/actor/playground/mixed_automation.py b/browser_use/actor/playground/mixed_automation.pyindex f164e7249..86f63f758 100644--- a/browser_use/actor/playground/mixed_automation.py+++ b/browser_use/actor/playground/mixed_automation.py@@ -38,7 +38,7 @@ async def main():await asyncio.sleep(1)- element = await target.getElementByPrompt('zip code input', llm)+ element = await target.get_element_by_prompt('zip code input', llm)print('Element found', element)diff --git a/browser_use/actor/playground/playground.py b/browser_use/actor/playground/playground.pyindex 91f3753c5..551df560e 100755--- a/browser_use/actor/playground/playground.py+++ b/browser_use/actor/playground/playground.py@@ -37,8 +37,8 @@ async def main():target = await browser.newTarget('https://en.wikipedia.org')# Get basic page info- url = await target.getUrl()- title = await target.getTitle()+ url = await target.get_url()+ title = await target.get_title()logger.info(f'📄 Page loaded: {title} ({url})')# Take a screenshot@@ -48,7 +48,7 @@ async def main():# Set viewport sizelogger.info('🖥️ Setting viewport to 1920x1080...')- await target.setViewportSize(1920, 1080)+ await target.set_viewport_size(1920, 1080)# Execute some JavaScript to count linkslogger.info('🔍 Counting article links using JavaScript...')@@ -71,7 +71,7 @@ async def main():# Try to find and interact with links using CSS selectortry:# Find article links on the page- links = await target.getElementsByCSSSelector('a[href*="/wiki/"]:not([href*=":"])')+ links = await target.get_elements_by_css_selector('a[href*="/wiki/"]:not([href*=":"])')if links:logger.info(f'📋 Found {len(links)} wiki links via CSS selector')@@ -80,8 +80,8 @@ async def main():link_element = links[0]# Get link info using available methods- basic_info = await link_element.getBasicInfo()- link_href = await link_element.getAttribute('href')+ basic_info = await link_element.get_basic_info()+ link_href = await link_element.get_attribute('href')logger.info(f'🎯 Selected element: <{basic_info["nodeName"]}>')logger.info(f'🔗 Link href: {link_href}')@@ -107,8 +107,8 @@ async def main():await asyncio.sleep(3)# Get new page info- new_url = await target.getUrl()- new_title = await target.getTitle()+ new_url = await target.get_url()+ new_title = await target.get_title()logger.info(f'📄 Navigated to: {new_title}')logger.info(f'🌐 New URL: {new_url}')else:@@ -157,7 +157,7 @@ async def main():# Get page title using different methodstitle_via_js = await target.evaluate('() => document.title')- title_via_api = await target.getTitle()+ title_via_api = await target.get_title()logger.info(f'📝 Title via JS: "{title_via_js}"')logger.info(f'📝 Title via API: "{title_via_api}"')@@ -169,11 +169,11 @@ async def main():# Test browser navigation with error handlinglogger.info('⬅️ Testing browser back navigation...')try:- await target.goBack()+ await target.go_back()await asyncio.sleep(2)- back_url = await target.getUrl()- back_title = await target.getTitle()+ back_url = await target.get_url()+ back_title = await target.get_title()logger.info(f'📄 After going back: {back_title}')logger.info(f'🌐 Back URL: {back_url}')except RuntimeError as e:@@ -182,7 +182,7 @@ async def main():# Test creating new targetlogger.info('🆕 Creating new blank target...')new_target = await browser.newTarget()- new_target_url = await new_target.getUrl()+ new_target_url = await new_target.get_url()logger.info(f'🆕 New target created with URL: {new_target_url}')# Get all targets@@ -192,7 +192,7 @@ async def main():# Test form interaction if we can find a formtry:# Look for search input on the page- search_inputs = await target.getElementsByCSSSelector('input[type="search"], input[name*="search"]')+ search_inputs = await target.get_elements_by_css_selector('input[type="search"], input[name*="search"]')if search_inputs:search_input = search_inputs[0]diff --git a/browser_use/actor/target.py b/browser_use/actor/target.pyindex 554714b58..163ed853c 100644--- a/browser_use/actor/target.py+++ b/browser_use/actor/target.py@@ -88,7 +88,7 @@ class Target:session_id = await self._ensure_session()await self._client.send.Page.reload(session_id=session_id)- async def getElement(self, backend_node_id: int) -> 'Element':+ async def get_element(self, backend_node_id: int) -> 'Element':"""Get an element by its backend node ID."""session_id = await self._ensure_session()@@ -240,7 +240,7 @@ class Target:key_up_params: 'DispatchKeyEventParameters' = {'type': 'keyUp', 'key': key}await self._client.send.Input.dispatchKeyEvent(key_up_params, session_id=session_id)- async def setViewportSize(self, width: int, height: int) -> None:+ async def set_viewport_size(self, width: int, height: int) -> None:"""Set the viewport size."""session_id = await self._ensure_session()@@ -256,20 +256,20 @@ class Target:)# Target properties (from CDP getTargetInfo)- async def getTargetInfo(self) -> 'TargetInfo':+ async def get_target_info(self) -> 'TargetInfo':"""Get target information."""params: 'GetTargetInfoParameters' = {'targetId': self._target_id}result = await self._client.send.Target.getTargetInfo(params)return result['targetInfo']- async def getUrl(self) -> str:+ async def get_url(self) -> str:"""Get the current URL."""- info = await self.getTargetInfo()+ info = await self.get_target_info()return info.get('url', '')- async def getTitle(self) -> str:+ async def get_title(self) -> str:"""Get the current title."""- info = await self.getTargetInfo()+ info = await self.get_target_info()return info.get('title', '')async def goto(self, url: str) -> None:@@ -279,7 +279,7 @@ class Target:params: 'NavigateParameters' = {'url': url}await self._client.send.Page.navigate(params, session_id=session_id)- async def goBack(self) -> None:+ async def go_back(self) -> None:"""Navigate back in history."""session_id = await self._ensure_session()@@ -301,7 +301,7 @@ class Target:except Exception as e:raise RuntimeError(f'Failed to navigate back: {e}')- async def goForward(self) -> None:+ async def go_forward(self) -> None:"""Navigate forward in history."""session_id = await self._ensure_session()@@ -324,7 +324,7 @@ class Target:raise RuntimeError(f'Failed to navigate forward: {e}')# Element finding methods (these would need to be implemented based on DOM queries)- async def getElementsByCSSSelector(self, selector: str) -> list['Element']:+ async def get_elements_by_css_selector(self, selector: str) -> list['Element']:"""Get elements by CSS selector."""session_id = await self._ensure_session()@@ -356,7 +356,7 @@ class Target:"""Get the DOM service for this target."""return DomService(self._browser_session)- async def getElementByPrompt(self, prompt: str, llm: 'BaseChatModel | None' = None) -> 'Element | None':+ async def get_element_by_prompt(self, prompt: str, llm: 'BaseChatModel | None' = None) -> 'Element | None':"""Get an element by a prompt."""await self._ensure_session()llm = llm or self._llm@@ -435,12 +435,12 @@ Before you return the element index, reason about the state and elements for a sreturn Element(self._browser_session, element.backend_node_id, self._session_id)- async def mustGetElementByPrompt(self, prompt: str, llm: 'BaseChatModel | None' = None) -> 'Element':+ async def must_get_element_by_prompt(self, prompt: str, llm: 'BaseChatModel | None' = None) -> 'Element':"""Get an element by a prompt.@dev LLM can still return None, this just raises an error if the element is not found."""- element = await self.getElementByPrompt(prompt, llm)+ element = await self.get_element_by_prompt(prompt, llm)if element is None:raise ValueError(f'No element found for prompt: {prompt}')