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
handling multiple elements with the same text
jersobh4a201f4c6938
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 06dde8949..8f6facc76 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -1106,23 +1106,38 @@ class BrowserContext:return None@time_execution_async('--get_locate_element_by_text')- async def get_locate_element_by_text(self, text: str) -> Optional[ElementHandle]:+ async def get_locate_element_by_text(self, text: str, nth: Optional[int] = 0) -> Optional[ElementHandle]:"""Locates an element on the page using the provided text.+ If `nth` is provided, it returns the nth matching element (0-based)."""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+ elements = await current_frame.query_selector_all(f"text={text}")+ # considering only visible elements+ elements = [el for el in elements if await el.is_visible()]++ if not elements:+ logger.error(f"No visible element with text '{text}' found.")+ return None++ if nth is not None:+ if 0 <= nth < len(elements):+ element_handle = elements[nth]+ else:+ logger.error(f"Visible element with text '{text}' not found at index {nth}.")+ return None+ else:+ element_handle = elements[0]++ await element_handle.scroll_into_view_if_needed()+ return element_handleexcept 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.pyindex 6a61e6f44..1746fe4e5 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -157,6 +157,7 @@ class Controller(Generic[Context]):if element_node:await element_node.click()msg = f'🖱️ Clicked on element with selector {params.css_selector}'+ return ActionResult(extracted_content=msg, include_in_memory=True)except Exception as e:logger.warning(f'Element not clickable with selector {params.css_selector} - most likely the page changed')return ActionResult(error=str(e))@@ -168,6 +169,7 @@ class Controller(Generic[Context]):if element_node:await element_node.click()msg = f'🖱️ Clicked on element with xpath {params.xpath}'+ return ActionResult(extracted_content=msg, include_in_memory=True)except Exception as e:logger.warning(f'Element not clickable with xpath {params.xpath} - most likely the page changed')return ActionResult(error=str(e))@@ -175,12 +177,19 @@ class Controller(Generic[Context]):@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)+ element_node = await browser.get_locate_element_by_text(+ text=params.text,+ nth=params.nth,+ )+if element_node:await element_node.click()msg = f'🖱️ Clicked on element with text {params.text}'+ return ActionResult(extracted_content=msg, include_in_memory=True)+ else:+ return ActionResult(error=f"No element found for text '{params.text}'")except Exception as e:- logger.warning(f'Element not clickable with text {params.text} - most likely the page changed')+ logger.warning(f"Element not clickable with text {params.text} - {e}")return ActionResult(error=str(e))@self.registry.action(diff --git a/browser_use/controller/views.py b/browser_use/controller/views.pyindex f6fa16104..8577784d0 100644--- a/browser_use/controller/views.py+++ b/browser_use/controller/views.py@@ -24,6 +24,7 @@ class ClickElementBySelectorAction(BaseModel):class ClickElementByTextAction(BaseModel):text: str+ nth: int = 0class InputTextAction(BaseModel):index: intdiff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.pynew file mode 100644index 000000000..e770f2362--- /dev/null+++ b/examples/custom-functions/hover_element.py@@ -0,0 +1,88 @@+import os+import sys+from pathlib import Path+from typing import Optional++from pydantic import BaseModel++from browser_use.agent.views import ActionResult++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import asyncio++from langchain_openai import ChatOpenAI++from browser_use import Agent, Controller+from browser_use.browser.browser import Browser, BrowserConfig+from browser_use.browser.context import BrowserContext++class HoverAction(BaseModel):+ index: Optional[int] = None+ xpath: Optional[str] = None+ selector: Optional[str] = None++browser = Browser(+ config=BrowserConfig(+ headless=False,+ )+)+controller = Controller()++ 'Hover over an element',+ param_model=HoverAction, # Define this model with at least "index: int" field+)+async def hover_element(params: HoverAction, browser: BrowserContext):+ """+ Hovers over the element specified by its index from the cached selector map or by XPath.+ """+ session = await browser.get_session()+ state = session.cached_state++ if params.xpath:+ # Use XPath to locate the element+ element_handle = await browser.get_locate_element_by_xpath(params.xpath)+ if element_handle is None:+ raise Exception(f'Failed to locate element with XPath {params.xpath}')+ elif params.selector:+ # Use CSS selector to locate the element+ element_handle = await browser.get_locate_element_by_css_selector(params.selector)+ if element_handle is None:+ raise Exception(f'Failed to locate element with CSS Selector {params.selector}')+ elif params.index is not None:+ # Use index to locate the element+ if state is None or params.index not in state.selector_map:+ raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')+ element_node = state.selector_map[params.index]+ element_handle = await browser.get_locate_element(element_node)+ if element_handle is None:+ raise Exception(f'Failed to locate element with index {params.index}')+ else:+ raise Exception('Either index or xpath must be provided')++ try:+ await element_handle.hover()+ msg = f'🖱️ Hovered over element at index {params.index}' if params.index is not None else f'🖱️ Hovered over element with XPath {params.xpath}'+ return ActionResult(extracted_content=msg, include_in_memory=True)+ except Exception as e:+ err_msg = f'❌ Failed to hover over element: {str(e)}'+ raise Exception(err_msg)++async def main():+ task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the css selector #hoverdivpara, then click on "Can you click me?"'+ # task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the xpath //*[@id="hoverdivpara"], then click on "Can you click me?"'+ model = ChatOpenAI(model='gpt-4o')+ agent = Agent(+ task=task,+ llm=model,+ controller=controller,+ browser=browser,+ )++ await agent.run()+ await browser.close()++ input('Press Enter to close...')++if __name__ == '__main__':+ asyncio.run(main())\ No newline at end of filediff --git a/examples/features/click_fallback_options.py b/examples/features/click_fallback_options.pyindex 2a03eaede..4721bba9a 100644--- a/examples/features/click_fallback_options.py+++ b/examples/features/click_fallback_options.py@@ -5,6 +5,8 @@ import asynciofrom aiohttp import web # make sure to install aiohttp: pip install aiohttpfrom dotenv import load_dotenvfrom langchain_openai import ChatOpenAI+# from langchain_google_genai import ChatGoogleGenerativeAI+# Adjust path if necessarysys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))@@ -19,20 +21,20 @@ HTML_CONTENT = """<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;+ margin-bottom: 20px;}- /* 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%;@@ -46,12 +48,12 @@ HTML_CONTENT = """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;}@@ -63,47 +65,85 @@ HTML_CONTENT = """<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 class="select-option" data-value="option3">Pineapples</div>+ </div>+ </div>++ <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">Pineapples</div>+ </div>+ </div>++ <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">Pineapples</div>+ </div>+ </div>++ <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">Pineapples</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>+ <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';- });+ document.querySelectorAll('.custom-select').forEach(customSelect => {+ const selectDisplay = customSelect.querySelector('.select-display');+ const selectOptions = customSelect.querySelector('.select-options');+ const options = customSelect.querySelectorAll('.select-option');++ selectDisplay.addEventListener('click', (e) => {+ // Close all other dropdowns+ document.querySelectorAll('.select-options').forEach(opt => {+ if (opt !== selectOptions) opt.style.display = 'none';+ });- // 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';+ // Toggle current dropdown+ const isVisible = selectOptions.style.display === 'block';+ selectOptions.style.display = isVisible ? 'none' : 'block';++ e.stopPropagation();+ });++ 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';- }+ // Close all dropdowns if clicking outside+ document.addEventListener('click', () => {+ document.querySelectorAll('.select-options').forEach(opt => {+ opt.style.display = 'none';+ });});</script></body></html>+"""# aiohttp request handler to serve the HTML content@@ -134,14 +174,18 @@ async def main():# 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'+ text_task = 'Open http://localhost:8000/, click the third element with the text "Select a fruit" and then click on Apples, then click the second 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')+ # llm = ChatGoogleGenerativeAI(+ # model="gemini-2.0-flash-lite",+ # )+# Run different agent tasks.- for task in [text_task, css_selector_task, xpath_task, text_task, select_task, button_task]:+ for task in [xpath_task, css_selector_task, text_task, select_task, button_task]:agent = Agent(task=task,llm=llm,