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(cli): add wait command for selector and text conditions
ShawnPana33e03b7b0fe3
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex d360058b6..fba2c680a 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -507,6 +507,30 @@ class ClearCookiesEvent(BaseEvent[None]):event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_ClearCookiesEvent', 15.0))+# ============================================================================+# Wait Events+# ============================================================================+++class WaitForSelectorEvent(BaseEvent[bool]):+ """Wait for a CSS selector to appear on the page."""++ selector: str+ timeout_ms: int = 30000+ state: Literal['attached', 'detached', 'visible', 'hidden'] = 'visible'++ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_WaitForSelectorEvent', 60.0))+++class WaitForTextEvent(BaseEvent[bool]):+ """Wait for text to appear on the page."""++ text: str+ timeout_ms: int = 30000++ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_WaitForTextEvent', 60.0))++# ============================================================================# Storage State Events# ============================================================================diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex f79901d2f..eb8e926a6 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1487,6 +1487,13 @@ class BrowserSession(BaseModel):self._cookies_watchdog = CookiesWatchdog(event_bus=self.event_bus, browser_session=self)self._cookies_watchdog.attach_to_session()+ # Initialize WaitWatchdog (handles wait conditions for selectors and text)+ from browser_use.browser.watchdogs.wait_watchdog import WaitWatchdog++ WaitWatchdog.model_rebuild()+ self._wait_watchdog = WaitWatchdog(event_bus=self.event_bus, browser_session=self)+ self._wait_watchdog.attach_to_session()+# Mark watchdogs as attached to prevent duplicate attachmentself._watchdogs_attached = Truediff --git a/browser_use/browser/watchdogs/wait_watchdog.py b/browser_use/browser/watchdogs/wait_watchdog.pynew file mode 100644index 000000000..b90dbef0f--- /dev/null+++ b/browser_use/browser/watchdogs/wait_watchdog.py@@ -0,0 +1,121 @@+"""Wait watchdog for wait conditions (selector, text)."""++import asyncio+import json+from typing import Any, ClassVar++from bubus import BaseEvent++from browser_use.browser.events import (+ WaitForSelectorEvent,+ WaitForTextEvent,+)+from browser_use.browser.watchdog_base import BaseWatchdog+++class WaitWatchdog(BaseWatchdog):+ """Handles wait conditions for selectors and text."""++ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [+ WaitForSelectorEvent,+ WaitForTextEvent,+ ]+ EMITS: ClassVar[list[type[BaseEvent]]] = []++ async def _execute_js(self, js: str) -> Any:+ """Execute JavaScript in the browser context."""+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=None)+ if not cdp_session:+ raise RuntimeError('No active browser session')++ result = await cdp_session.cdp_client.send.Runtime.evaluate(+ params={'expression': js, 'returnByValue': True},+ session_id=cdp_session.session_id,+ )+ return result.get('result', {}).get('value')++ async def on_WaitForSelectorEvent(self, event: WaitForSelectorEvent) -> bool:+ """Wait for a CSS selector to match an element in the specified state."""+ try:+ timeout_seconds = event.timeout_ms / 1000.0+ poll_interval = 0.1 # 100ms polling+ elapsed = 0.0++ while elapsed < timeout_seconds:+ # Check based on state+ if event.state == 'attached':+ js = f'document.querySelector({json.dumps(event.selector)}) !== null'+ elif event.state == 'detached':+ js = f'document.querySelector({json.dumps(event.selector)}) === null'+ elif event.state == 'visible':+ js = f'''+ (function() {{+ const el = document.querySelector({json.dumps(event.selector)});+ if (!el) return false;+ const style = window.getComputedStyle(el);+ const rect = el.getBoundingClientRect();+ return style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ style.opacity !== '0' &&+ rect.width > 0 &&+ rect.height > 0;+ }})()+ '''+ elif event.state == 'hidden':+ js = f'''+ (function() {{+ const el = document.querySelector({json.dumps(event.selector)});+ if (!el) return true;+ const style = window.getComputedStyle(el);+ const rect = el.getBoundingClientRect();+ return style.display === 'none' ||+ style.visibility === 'hidden' ||+ style.opacity === '0' ||+ rect.width === 0 ||+ rect.height === 0;+ }})()+ '''+ else:+ js = f'document.querySelector({json.dumps(event.selector)}) !== null'++ result = await self._execute_js(js)+ if result:+ self.logger.debug(f'[WaitWatchdog] Selector matched: {event.selector} (state: {event.state})')+ return True++ await asyncio.sleep(poll_interval)+ elapsed += poll_interval++ self.logger.warning(f'[WaitWatchdog] Timeout waiting for selector: {event.selector}')+ return False+ except Exception as e:+ self.logger.error(f'[WaitWatchdog] Failed to wait for selector: {e}')+ return False++ async def on_WaitForTextEvent(self, event: WaitForTextEvent) -> bool:+ """Wait for text to appear on the page."""+ try:+ timeout_seconds = event.timeout_ms / 1000.0+ poll_interval = 0.1 # 100ms polling+ elapsed = 0.0++ while elapsed < timeout_seconds:+ js = f'''+ (function() {{+ const text = {json.dumps(event.text)};+ return document.body.innerText.includes(text);+ }})()+ '''+ result = await self._execute_js(js)+ if result:+ self.logger.debug(f'[WaitWatchdog] Text found: {event.text[:50]}...')+ return True++ await asyncio.sleep(poll_interval)+ elapsed += poll_interval++ self.logger.warning(f'[WaitWatchdog] Timeout waiting for text: {event.text[:50]}...')+ return False+ except Exception as e:+ self.logger.error(f'[WaitWatchdog] Failed to wait for text: {e}')+ return Falsediff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.pyindex 9905a198b..fb4f20f5a 100644--- a/browser_use/skill_cli/commands/browser.py+++ b/browser_use/skill_cli/commands/browser.py@@ -25,6 +25,7 @@ COMMANDS = {'eval','extract','cookies',+ 'wait',}@@ -231,4 +232,32 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'error': 'Invalid cookies command. Use: get, set, clear'}+ elif action == 'wait':+ wait_command = params.get('wait_command')++ if wait_command == 'selector':+ from browser_use.browser.events import WaitForSelectorEvent++ event = WaitForSelectorEvent(+ selector=params['selector'],+ timeout_ms=params.get('timeout', 30000),+ state=params.get('state', 'visible'),+ )+ await bs.event_bus.dispatch(event)+ success = await event.event_result()+ return {'selector': params['selector'], 'found': success}++ elif wait_command == 'text':+ from browser_use.browser.events import WaitForTextEvent++ event = WaitForTextEvent(+ text=params['text'],+ timeout_ms=params.get('timeout', 30000),+ )+ await bs.event_bus.dispatch(event)+ success = await event.event_result()+ return {'text': params['text'], 'found': success}++ return {'error': 'Invalid wait command. Use: selector, text'}+raise ValueError(f'Unknown browser action: {action}')diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 561c11706..ddf25a35c 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -290,6 +290,24 @@ Examples:p = cookies_sub.add_parser('clear', help='Clear cookies')p.add_argument('--url', help='Clear only for URL')+ # -------------------------------------------------------------------------+ # Wait Commands+ # -------------------------------------------------------------------------++ wait_p = subparsers.add_parser('wait', help='Wait for conditions')+ wait_sub = wait_p.add_subparsers(dest='wait_command')++ # wait selector <css>+ p = wait_sub.add_parser('selector', help='Wait for CSS selector')+ p.add_argument('selector', help='CSS selector')+ p.add_argument('--timeout', type=int, default=30000, help='Timeout in ms')+ p.add_argument('--state', choices=['attached', 'detached', 'visible', 'hidden'], default='visible', help='Element state')++ # wait text <text>+ p = wait_sub.add_parser('text', help='Wait for text')+ p.add_argument('text', help='Text to wait for')+ p.add_argument('--timeout', type=int, default=30000, help='Timeout in ms')+# -------------------------------------------------------------------------# Python Execution# -------------------------------------------------------------------------diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex a5d42d037..be919b1ed 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -104,6 +104,15 @@ browser-use cookies clear # Clear all cookiesbrowser-use cookies clear --url <url> # Clear cookies for specific URL```+### Wait Conditions+```bash+browser-use wait selector "h1" # Wait for element to be visible+browser-use wait selector ".loading" --state hidden # Wait for element to disappear+browser-use wait selector "#btn" --state attached # Wait for element in DOM+browser-use wait text "Success" # Wait for text to appear+browser-use wait selector "h1" --timeout 5000 # Custom timeout in ms+```+### Python Execution (Persistent Session)```bashbrowser-use python "x = 42" # Set variable