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
v2
Gregor Žuniče0f65ca892b9
diff --git a/browser_use/actor/README.md b/browser_use/actor/README.mdindex 162f7fcc2..c7bd728bc 100644--- a/browser_use/actor/README.md+++ b/browser_use/actor/README.md@@ -4,17 +4,31 @@ Browser Actor is a web automation library built directly on CDP.## Usage+### Option 1: Direct CDP Usage```pythonfrom cdp_use import CDPClient-from browser_use.actor import Browser, Target, Element, Mouse+from browser_use.actor import Target, Element, Mouse-# Create client and browser+# Create client directly - no Browser class neededclient = CDPClient(ws_url)-browser = Browser(client)```+### Option 2: Integrated with Browser (Recommended)```python-# Get targets (multiple ways)+from browser_use import Browser++# Create and start browser session+browser = Browser()+await browser.start()`++# Use integrated browser methods directly+target = await browser.newTarget("https://example.com")+targets = await browser.getTargets()+current_target = await browser.get_current_target()+```++```python+# Get targets (multiple ways) - using browser methodstarget = await browser.newTarget() # Create blank tabtarget = await browser.newTarget("https://example.com") # Create tab with URLtargets = await browser.getTargets() # Get all existing tabs@@ -69,19 +83,21 @@ await target.reload()page_screenshot = await target.screenshot() # JPEG by defaultpage_png = await target.screenshot(format="png")```-Ø+## Core Classes-- **Browser**, **Target**, **Element**, **Mouse**: Core classes for browser operations+- **Browser**: Main browser session with integrated browser methods+- **Target**, **Element**, **Mouse**: Core classes for browser operations## API Reference-### Browser Methods+### 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- `cookies(urls=None)` → `list[Cookie]` - Get cookies for specified URLs (or all if None)- `clearCookies()` - Clear all cookies+- `get_current_target()` → `Target | None` - Get the current target### Target Methods- `getElementsByCSSSelector(selector: str)` → `list[Element]` - Find elements by CSS selectordiff --git a/browser_use/actor/__init__.py b/browser_use/actor/__init__.pyindex 922ad703b..176a51c41 100644--- a/browser_use/actor/__init__.py+++ b/browser_use/actor/__init__.py@@ -3,9 +3,8 @@A Playwright-like library built on top of CDP (Chrome DevTools Protocol)."""-from .browser import Browserfrom .element import Elementfrom .mouse import Mousefrom .target import Target-__all__ = ['Browser', 'Target', 'Element', 'Mouse']+__all__ = ['Target', 'Element', 'Mouse']diff --git a/browser_use/actor/browser.py b/browser_use/actor/browser.pydeleted file mode 100644index 390302c2b..000000000--- a/browser_use/actor/browser.py+++ /dev/null@@ -1,73 +0,0 @@-"""Browser class for high-level CDP operations."""--from typing import TYPE_CHECKING, Union--if TYPE_CHECKING:- from cdp_use.cdp.network.library import GetCookiesParameters- from cdp_use.cdp.network.types import Cookie- from cdp_use.cdp.target.commands import (- CloseTargetParameters,- CreateTargetParameters,- )- from cdp_use.client import CDPClient-- from .target import Target---class Browser:- """High-level browser interface built on CDP."""-- def __init__(self, client: 'CDPClient'):- self._client = client-- async def newTarget(self, url: str | None = None) -> 'Target':- """Create a new target (tab)."""- params: 'CreateTargetParameters' = {'url': url or 'about:blank'}- result = await self._client.send.Target.createTarget(params)-- target_id = result['targetId']-- # Import here to avoid circular import- from .target import Target-- return Target(self._client, target_id)-- async def getTargets(self) -> list['Target']:- """Get all available targets."""- result = await self._client.send.Target.getTargets()-- targets = []- # Import here to avoid circular import- from .target import Target-- for target_info in result['targetInfos']:- if target_info['type'] in ['page', 'iframe']:- targets.append(Target(self._client, target_info['targetId']))-- return targets-- async def closeTarget(self, target: Union['Target', str]) -> None:- """Close a target by Target object or target ID."""- # Import here to avoid circular import- from .target import Target-- if isinstance(target, Target):- target_id = target._target_id- else:- target_id = str(target)-- params: 'CloseTargetParameters' = {'targetId': target_id}- await self._client.send.Target.closeTarget(params)-- async def cookies(self, urls: list[str] | None = None) -> list[Cookie]:- """Get cookies, optionally filtered by URLs."""- params: GetCookiesParameters = {}- if urls:- params['urls'] = urls-- result = await self._client.send.Network.getCookies(params)- return result['cookies']-- async def clearCookies(self) -> None:- """Clear all cookies."""- await self._client.send.Network.clearBrowserCookies()diff --git a/browser_use/actor/playground/mixed_automation.py b/browser_use/actor/playground/mixed_automation.pynew file mode 100644index 000000000..1c8f28807--- /dev/null+++ b/browser_use/actor/playground/mixed_automation.py@@ -0,0 +1,60 @@+import asyncio++from pydantic import BaseModel++from browser_use import Agent, Browser++TASK = """+On the current wikipedia page, find the latest huge edit and tell me what is was about.+"""+++class LatestEditFinder(BaseModel):+ """Find the latest huge edit on the current wikipedia page."""++ latest_edit: str+ edit_time: str+ edit_author: str+ edit_summary: str+ edit_url: str+++async def main():+ """+ Main function demonstrating mixed automation with Browser-Use and Playwright.+ """+ print('🚀 Mixed Automation with Browser-Use and Actor API')++ browser = Browser(keep_alive=True)+ await browser.start()++ apple_target = await browser.get_current_target() or await browser.newTarget()++ # Go to apple wikipedia page+ await apple_target.goto('https://en.wikipedia.org/wiki/Apple_Inc.')++ await asyncio.sleep(1)++ element = await apple_target.getElementsByCSSSelector(+ '#mw-content-text > div.mw-content-ltr.mw-parser-output > p:nth-child(8) > a:nth-child(3)'+ )++ if first_element := element[0]:+ print('Element found', first_element)+ await first_element.click()+ else:+ print('No element found')++ agent = Agent(+ task='clic on the button that says "technology company"',+ browser=browser,+ )+ output = await agent.run(max_steps=1)++ await asyncio.sleep(10)++ await browser.stop()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/browser_use/actor/playground/playground.py b/browser_use/actor/playground/playground.pyindex 2f126f3e0..91f3753c5 100755--- a/browser_use/actor/playground/playground.py+++ b/browser_use/actor/playground/playground.py@@ -13,8 +13,7 @@ import asyncioimport jsonimport logging-from browser_use.actor import Browser-from browser_use.browser.session import BrowserSession+from browser_use import Browser# Configure logging to see what's happeninglogging.basicConfig(level=logging.INFO)@@ -26,20 +25,14 @@ async def main():logger.info('🚀 Starting browser actor playground')# Create browser session- browser_session = BrowserSession()+ browser = Browser()try:# Start the browser- await browser_session.start()+ await browser.start()logger.info('✅ Browser session started')- # Get the CDP client from the session- cdp_client = browser_session.cdp_client-- # Create the actor browser interface- browser = Browser(cdp_client)-- # Navigate to Wikipedia+ # Navigate to Wikipedia using integrated methodslogger.info('📖 Navigating to Wikipedia...')target = await browser.newTarget('https://en.wikipedia.org')@@ -233,7 +226,7 @@ async def main():# Clean uplogger.info('🧹 Cleaning up...')try:- await browser_session.stop()+ await browser.stop()logger.info('✅ Browser session stopped')except Exception as e:logger.error(f'❌ Error stopping browser: {e}')diff --git a/browser_use/actor/target.py b/browser_use/actor/target.pyindex d481556be..630fdd315 100644--- a/browser_use/actor/target.py+++ b/browser_use/actor/target.py@@ -52,6 +52,14 @@ class Target:return self._session_id+ @property+ async def session_id(self) -> str:+ """Get the session ID for this target.++ @dev Pass this to an arbitrary CDP call+ """+ return await self._ensure_session()+@propertyasync def mouse(self) -> 'Mouse':"""Get the mouse interface for this target."""diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 543119ec8..f98546c50 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -1641,8 +1641,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):cached_selector_map = {}cached_element_hashes = set()- # await self.browser_session.remove_highlights()-for i, action in enumerate(actions):if i > 0:# ONLY ALLOW TO CALL `done` IF IT IS A SINGLE ACTIONdiff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 6075448ad..5534be622 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -4,7 +4,7 @@ import asyncioimport loggingfrom functools import cached_propertyfrom pathlib import Path-from typing import Any, Literal, Self, cast+from typing import TYPE_CHECKING, Any, Literal, Self, Union, castimport httpxfrom bubus import EventBus@@ -42,6 +42,9 @@ from browser_use.dom.views import EnhancedDOMTreeNode, TargetInfofrom browser_use.observability import observe_debugfrom browser_use.utils import _log_pretty_url, is_new_tab_page+if TYPE_CHECKING:+ from browser_use.actor.target import Target+DEFAULT_BROWSER_PROFILE = BrowserProfile()_LOGGED_UNIQUE_SESSION_IDS = set() # track unique session IDs that have been logged to make sure we always assign a unique enough id to new sessions and avoid ambiguity in logs@@ -834,12 +837,82 @@ class BrowserSession(BaseModel):))+ # region - ========== CDP-based replacements for browser_context operations ==========@propertydef cdp_client(self) -> CDPClient:"""Get the cached root CDP cdp_session.cdp_client. The client is created and started in self.connect()."""assert self._cdp_client_root is not None, 'CDP client not initialized - browser may not be connected yet'return self._cdp_client_root+ async def newTarget(self, url: str | None = None) -> 'Target':+ """Create a new target (tab)."""+ from cdp_use.cdp.target.commands import CreateTargetParameters++ params: CreateTargetParameters = {'url': url or 'about:blank'}+ result = await self.cdp_client.send.Target.createTarget(params)++ target_id = result['targetId']++ # Import here to avoid circular import+ from browser_use.actor.target import Target++ return Target(self.cdp_client, target_id)++ async def get_current_target(self) -> 'Target | None':+ """Get the current target as an actor Target."""+ target_info = await self.get_current_target_info()++ if not target_info:+ return None++ from browser_use.actor.target import Target++ return Target(self.cdp_client, target_info['targetId'])++ async def getTargets(self) -> list['Target']:+ """Get all available targets."""+ result = await self.cdp_client.send.Target.getTargets()++ targets = []+ # Import here to avoid circular import+ from browser_use.actor.target import Target++ for target_info in result['targetInfos']:+ if target_info['type'] in ['page', 'iframe']:+ targets.append(Target(self.cdp_client, target_info['targetId']))++ return targets++ async def closeTarget(self, target: 'Union[Target, str]') -> None:+ """Close a target by Target object or target ID."""+ from cdp_use.cdp.target.commands import CloseTargetParameters++ # Import here to avoid circular import+ from browser_use.actor.target import Target++ if isinstance(target, Target):+ target_id = target._target_id+ else:+ target_id = str(target)++ params: CloseTargetParameters = {'targetId': target_id}+ await self.cdp_client.send.Target.closeTarget(params)++ async def cookies(self, urls: list[str] | None = None) -> list['Cookie']:+ """Get cookies, optionally filtered by URLs."""+ from cdp_use.cdp.network.library import GetCookiesParameters++ params: GetCookiesParameters = {}+ if urls:+ params['urls'] = urls++ result = await self.cdp_client.send.Network.getCookies(params)+ return result['cookies']++ async def clearCookies(self) -> None:+ """Clear all cookies."""+ await self.cdp_client.send.Network.clearBrowserCookies()+async def get_or_create_cdp_session(self, target_id: TargetID | None = None, focus: bool = True, new_socket: bool | None = None) -> CDPSession:@@ -920,7 +993,9 @@ class BrowserSession(BaseModel):def current_session_id(self) -> str | None:return self.agent_focus.session_id if self.agent_focus else None- # ========== Helper Methods ==========+ # endregion - ========== CDP-based ... ==========++ # region - ========== Helper Methods ==========@observe_debug(ignore_input=True, ignore_output=True, name='get_browser_state_summary')async def get_browser_state_summary(self,@@ -1455,8 +1530,9 @@ class BrowserSession(BaseModel):return tabs- # ========== ID Lookup Methods ==========+ # endregion - ========== Helper Methods ==========+ # region - ========== ID Lookup Methods ==========async def get_current_target_info(self) -> TargetInfo | None:"""Get info about the current active target using CDP."""if not self.agent_focus or not self.agent_focus.target_id:@@ -1496,7 +1572,9 @@ class BrowserSession(BaseModel):await eventawait event.event_result(raise_if_any=True, raise_if_none=False)- # ========== DOM Helper Methods ==========+ # endregion - ========== ID Lookup Methods ==========++ # region - ========== DOM Helper Methods ==========async def get_dom_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:"""Get DOM element by index.@@ -1677,7 +1755,9 @@ class BrowserSession(BaseModel):"""return self._downloaded_files.copy()- # ========== CDP-based replacements for browser_context operations ==========+ # endregion - ========== Helper Methods ==========++ # region - ========== CDP-based replacements for browser_context operations ==========async def _cdp_get_all_pages(self,