Skip to content

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

Clicking by xpath, css selector or text

jersobh63f54cc10061
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 0fb40ae6f..06dde8949 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -1069,6 +1069,60 @@ class BrowserContext:
logger.error(f'Failed to locate element: {str(e)}')
return None
+ @time_execution_async('--get_locate_element_by_xpath')
+ async def get_locate_element_by_xpath(self, xpath: str) -> Optional[ElementHandle]:
+ """
+ Locates an element on the page using the provided XPath.
+ """
+ current_frame = await self.get_current_page()
+
+ try:
+ # Use XPath to locate the element
+ element_handle = await current_frame.query_selector(f'xpath={xpath}')
+ if element_handle:
+ await element_handle.scroll_into_view_if_needed()
+ return element_handle
+ return None
+ except Exception as e:
+ logger.error(f'Failed to locate element by XPath {xpath}: {str(e)}')
+ return None
+
+ @time_execution_async('--get_locate_element_by_css_selector')
+ async def get_locate_element_by_css_selector(self, css_selector: str) -> Optional[ElementHandle]:
+ """
+ Locates an element on the page using the provided CSS selector.
+ """
+ current_frame = await self.get_current_page()
+
+ try:
+ # Use CSS selector to locate the element
+ element_handle = await current_frame.query_selector(css_selector)
+ if element_handle:
+ await element_handle.scroll_into_view_if_needed()
+ return element_handle
+ return None
+ except Exception as e:
+ logger.error(f'Failed to locate element by CSS selector {css_selector}: {str(e)}')
+ return None
+
+ @time_execution_async('--get_locate_element_by_text')
+ async def get_locate_element_by_text(self, text: str) -> Optional[ElementHandle]:
+ """
+ Locates an element on the page using the provided text.
+ """
+ current_frame = await self.get_current_page()
+ try:
+ # Use Playwright's text selector syntax to locate the element
+ element_handle = await current_frame.query_selector(f"text={text}")
+ if element_handle:
+ await element_handle.scroll_into_view_if_needed()
+ return element_handle
+ return None
+ except Exception as e:
+ logger.error(f"Failed to locate element by text '{text}': {str(e)}")
+ return None
+
+
@time_execution_async('--input_text_element_node')
async def _input_text_element_node(self, element_node: DOMElementNode, text: str):
"""
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index cf468f287..7804b60d4 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -15,6 +15,9 @@ from browser_use.browser.context import BrowserContext
from browser_use.controller.registry.service import Registry
from browser_use.controller.views import (
ClickElementAction,
+ ClickElementBySelectorAction,
+ ClickElementByTextAction,
+ ClickElementByXpathAction,
DoneAction,
GoToUrlAction,
InputTextAction,
@@ -110,8 +113,8 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=msg, include_in_memory=True)
# Element Interaction Actions
- @self.registry.action('Click element', param_model=ClickElementAction)
- async def click_element(params: ClickElementAction, browser: BrowserContext):
+ @self.registry.action('Click element by index', param_model=ClickElementAction)
+ async def click_element_by_index(params: ClickElementAction, browser: BrowserContext):
session = await browser.get_session()
if params.index not in await browser.get_selector_map():
@@ -147,6 +150,39 @@ class Controller(Generic[Context]):
logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
return ActionResult(error=str(e))
+ @self.registry.action('Click element by selector', param_model=ClickElementBySelectorAction)
+ async def click_element_by_selector(params: ClickElementBySelectorAction, browser: BrowserContext):
+ try:
+ element_node = await browser.get_locate_element_by_css_selector(params.css_selector)
+ if element_node:
+ await element_node.click()
+ msg = f'🖱️ Clicked on element with selector {params.css_selector}'
+ except Exception as e:
+ logger.warning(f'Element not clickable with index {params.css_selector} - most likely the page changed')
+ return ActionResult(error=str(e))
+
+ @self.registry.action('Click on element by xpath', param_model=ClickElementByXpathAction)
+ async def click_element_by_xpath(params: ClickElementByXpathAction, browser: BrowserContext):
+ try:
+ element_node = await browser.get_locate_element_by_xpath(params.xpath)
+ if element_node:
+ await element_node.click()
+ msg = f'🖱️ Clicked on element with xpath {params.xpath}'
+ except Exception as e:
+ logger.warning(f'Element not clickable with xpath {params.xpath} - most likely the page changed')
+ return ActionResult(error=str(e))
+
+ @self.registry.action('Click element with text', param_model=ClickElementByTextAction)
+ async def click_element_by_text(params: ClickElementByTextAction, browser: BrowserContext):
+ try:
+ element_node = await browser.get_locate_element_by_text(params.text)
+ if element_node:
+ await element_node.click()
+ msg = f'🖱️ Clicked on element with text {params.text}'
+ except Exception as e:
+ logger.warning(f'Element not clickable with text {params.text} - most likely the page changed')
+ return ActionResult(error=str(e))
+
@self.registry.action(
'Input text into a input interactive element',
param_model=InputTextAction,
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 82995c9e3..f6fa16104 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -15,7 +15,15 @@ class GoToUrlAction(BaseModel):
class ClickElementAction(BaseModel):
index: int
xpath: Optional[str] = None
-
+
+class ClickElementByXpathAction(BaseModel):
+ xpath: str
+
+class ClickElementBySelectorAction(BaseModel):
+ css_selector: str
+
+class ClickElementByTextAction(BaseModel):
+ text: str
class InputTextAction(BaseModel):
index: int
diff --git a/examples/features/click_fallback_options.py b/examples/features/click_fallback_options.py
new file mode 100644
index 000000000..2a03eaede
--- /dev/null
+++ b/examples/features/click_fallback_options.py
@@ -0,0 +1,162 @@
+import os
+import sys
+import asyncio
+
+from aiohttp import web # make sure to install aiohttp: pip install aiohttp
+from dotenv import load_dotenv
+from langchain_openai import ChatOpenAI
+
+# Adjust path if necessary
+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from browser_use import Agent, Controller
+
+# Define a simple HTML page
+HTML_CONTENT = """
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Custom Select Div</title>
+ <style>
+ /* Container for the custom select */
+ .custom-select {
+ position: relative;
+ width: 200px;
+ font-family: Arial, sans-serif;
+ }
+ /* Display area showing the current selection */
+ .select-display {
+ padding: 10px;
+ border: 1px solid #ccc;
+ background-color: #fff;
+ cursor: pointer;
+ }
+ /* Dropdown options container */
+ .select-options {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ right: 0;
+ border: 1px solid #ccc;
+ border-top: none;
+ background-color: #fff;
+ display: none;
+ max-height: 150px;
+ overflow-y: auto;
+ z-index: 100;
+ }
+ /* Individual option styling */
+ .select-option {
+ padding: 10px;
+ cursor: pointer;
+ }
+ /* Hover effect for options */
+ .select-option:hover {
+ background-color: #f0f0f0;
+ }
+ </style>
+</head>
+<body>
+ <div class="custom-select">
+ <div class="select-display">Select a fruit</div>
+ <div class="select-options">
+ <div class="select-option" data-value="option1">Apples</div>
+ <div class="select-option" data-value="option2">Oranges</div>
+ <div class="select-option" data-value="option3">Pineaples</div>
+ </div>
+ </div>
+ <label for="cars">Choose a car:</label>
+ <select name="cars" id="cars">
+ <option value="volvo">Volvo</option>
+ <option value="bmw">BMW</option>
+ <option value="mercedes">Mercedes</option>
+ <option value="audi">Audi</option>
+</select>
+<button onclick="alert('I told you!')">Don't click me</button>
+ <script>
+ // Select DOM elements
+ const selectDisplay = document.querySelector('.select-display');
+ const selectOptions = document.querySelector('.select-options');
+ const options = document.querySelectorAll('.select-option');
+
+ // Toggle dropdown visibility when clicking on the display area
+ selectDisplay.addEventListener('click', () => {
+ const isVisible = selectOptions.style.display === 'block';
+ selectOptions.style.display = isVisible ? 'none' : 'block';
+ });
+
+ // Handle option click: update the display and hide the dropdown
+ options.forEach(option => {
+ option.addEventListener('click', () => {
+ selectDisplay.textContent = option.textContent;
+ selectDisplay.dataset.value = option.getAttribute('data-value');
+ selectOptions.style.display = 'none';
+ });
+ });
+
+ // Close the dropdown if clicking outside of it
+ document.addEventListener('click', (event) => {
+ if (!document.querySelector('.custom-select').contains(event.target)) {
+ selectOptions.style.display = 'none';
+ }
+ });
+ </script>
+</body>
+</html>
+"""
+
+# aiohttp request handler to serve the HTML content
+async def handle_root(request):
+ return web.Response(text=HTML_CONTENT, content_type='text/html')
+
+# Function to run the HTTP server
+async def run_http_server():
+ app = web.Application()
+ app.router.add_get("/", handle_root)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ site = web.TCPSite(runner, "localhost", 8000)
+ await site.start()
+ print("HTTP server running on http://localhost:8000")
+ # Keep the server running indefinitely.
+ while True:
+ await asyncio.sleep(3600)
+
+# Your agent tasks and other logic
+load_dotenv()
+controller = Controller()
+
+async def main():
+ # Start the HTTP server in the background.
+ server_task = asyncio.create_task(run_http_server())
+
+ # Example tasks for the agent.
+ xpath_task = 'Open http://localhost:8000/, click element with the xpath "/html/body/div/div[1]" and then click on Oranges'
+ css_selector_task = 'Open http://localhost:8000/, click element with the selector div.select-display and then click on apples'
+ text_task = 'Open http://localhost:8000/, click element with the text "Select a fruit" and then click on Oranges'
+ select_task = 'Open http://localhost:8000/, choose the car BMW'
+ button_task = 'Open http://localhost:8000/, click on the button'
+
+ llm = ChatOpenAI(model='gpt-4o')
+
+ # Run different agent tasks.
+ for task in [text_task, css_selector_task, xpath_task, text_task, select_task, button_task]:
+ agent = Agent(
+ task=task,
+ llm=llm,
+ controller=controller,
+ )
+ await agent.run()
+
+ # Wait for user input before shutting down.
+ input('Press Enter to close...')
+ # Cancel the server task once finished.
+ server_task.cancel()
+ try:
+ await server_task
+ except asyncio.CancelledError:
+ print("HTTP server stopped.")
+
+if __name__ == '__main__':
+ asyncio.run(main())