Skip to content

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

Added initial_actions and service action on registry for wait_for_element with timeout

jersobhac88cf46eebc
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 06d3b1e51..7ad0309ba 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -1137,3 +1137,17 @@ class BrowserContext:
screenshot=None,
tabs=[],
)
+
+ async def wait_for_element(self, selector: str, timeout: float) -> None:
+ """
+ Waits for an element matching the given CSS selector to become visible.
+
+ Args:
+ selector (str): The CSS selector of the element.
+ timeout (float): The maximum time to wait for the element to be visible (in milliseconds).
+
+ Raises:
+ 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)
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 722693fcf..6785b14f0 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -20,6 +20,7 @@ from browser_use.controller.views import (
SearchGoogleAction,
SendKeysAction,
SwitchTabAction,
+ WaitForElementAction,
)
from browser_use.utils import time_execution_async, time_execution_sync
@@ -81,6 +82,24 @@ class Controller:
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
+ @self.registry.action(
+ 'Wait for element to be visible',
+ param_model=WaitForElementAction, # Ensure this model is defined with "selector" and "timeout" fields
+ )
+ async def wait_for_element(params: WaitForElementAction, browser: BrowserContext):
+ """
+ Waits for the element specified by the CSS selector to become visible within the given timeout.
+ """
+ try:
+ await browser.wait_for_element(params.selector, params.timeout)
+ msg = f'👀 Element with selector "{params.selector}" became visible within {params.timeout}ms.'
+ logger.info(msg)
+ return ActionResult(extracted_content=msg, include_in_memory=True)
+ except Exception as e:
+ err_msg = f'❌ Failed to wait for element "{params.selector}" within {params.timeout}ms: {str(e)}'
+ logger.error(err_msg)
+ raise Exception(err_msg)
+
# Element Interaction Actions
@self.registry.action('Click element', param_model=ClickElementAction)
async def click_element(params: ClickElementAction, browser: BrowserContext):
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index d3cb11caf..c2a62a9c9 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -12,6 +12,10 @@ class GoToUrlAction(BaseModel):
url: str
+class WaitForElementAction(BaseModel):
+ selector: Optional[str] = None
+ timeout: int # Timeout in milliseconds
+
class ClickElementAction(BaseModel):
index: int
xpath: Optional[str] = None
diff --git a/tests/test_wait_for_element.py b/tests/test_wait_for_element.py
new file mode 100644
index 000000000..fc9b03489
--- /dev/null
+++ b/tests/test_wait_for_element.py
@@ -0,0 +1,67 @@
+import os
+import sys
+import asyncio
+
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+if project_root not in sys.path:
+ sys.path.insert(0, project_root)
+
+import pytest
+from dotenv import load_dotenv
+
+# Third-party imports
+from playwright.async_api import async_playwright
+from langchain_openai import ChatOpenAI
+
+# Local imports
+from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser.context import BrowserContext
+from browser_use import Agent, Controller
+
+# Load environment variables.
+load_dotenv()
+
+# Initialize language model and controller.
+llm = ChatOpenAI(model='gpt-4o')
+controller = Controller()
+
+async def test_wait_for_element():
+ """Test 'Wait for element' action."""
+
+ initial_actions = [
+ {'open_tab': {'url': 'https://pypi.org/'}},
+ # Uncomment the line below to include the wait action in initial actions.
+ # {'wait_for_element': {'selector': '#search', 'timeout': 30}},
+ ]
+
+ # Set up the browser context.
+ context = BrowserContext(
+ browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),
+ )
+
+ # Create the agent with the task.
+ agent = Agent(
+ task="Wait for element '#search' to be visible with a timeout of 30 seconds.",
+ llm=llm,
+ browser_context=context,
+ initial_actions=initial_actions,
+ controller=controller
+ )
+
+ # Run the agent for a few steps to trigger navigation and then the wait action.
+ history = await agent.run(max_steps=3)
+ action_names = history.action_names()
+
+ # Ensure that the wait_for_element action was executed.
+ assert 'wait_for_element' in action_names, "Expected wait_for_element action to be executed."
+
+ # Verify that the #search element is visible by querying the page.
+ page = await context.get_current_page()
+ header_handle = await page.query_selector("#search")
+ assert header_handle is not None, "Expected to find a #search element on the page."
+ is_visible = await header_handle.is_visible()
+ assert is_visible, "Expected the #search element to be visible."
+
+if __name__ == '__main__':
+ asyncio.run(test_wait_for_element())