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
Clicking works
magmueller9ea07f24ea38
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex 13a93368b..9761b2348 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -1,3 +1,5 @@+import time+from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC@@ -45,24 +47,76 @@ class BrowserActions:def click_element_by_index(self, index: int):"""- Clicks an element using its index from the selector map.+ Clicks an element using its index from the selector map with improved element finding strategies."""- if str(index) not in self.selector_map:+ if int(index) not in self.selector_map:+ print(f'Selector map: {self.selector_map}')raise Exception(f'Element index {index} not found in selector map')- xpath = self.selector_map[str(index)]- element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))- element.click()+ xpath = self.selector_map[int(index)]+ print(f"Trying to click element with xpath: {xpath}")++ # Wait for any overlays/popups to disappear+ time.sleep(2) # Brief wait for page to stabilize++ try:+ # Try multiple strategies to find the element+ for strategy in [+ lambda: self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath))),+ lambda: self.wait.until(EC.presence_of_element_located((By.XPATH, xpath))),+ lambda: self.driver.find_element(By.XPATH, xpath),+ # Try with simplified XPath+ lambda: self.wait.until(EC.element_to_be_clickable(+ (By.XPATH, f"//*[@id='{xpath.split('id=')[-1].split(']')[0]}']" if 'id=' in xpath else xpath)+ )),+ # Try finding by any visible matching element+ lambda: next(elem for elem in self.driver.find_elements(By.XPATH, "//*[not(ancestor-or-self::*[@style='display: none'])]")+ if elem.is_displayed() and elem.is_enabled())+ ]:+ try:+ element = strategy()+ if element and element.is_displayed() and element.is_enabled():+ # Scroll into view with JavaScript+ self.driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", element)+ time.sleep(0.5) # Wait for scroll to complete++ # Try both JavaScript click and regular click+ try:+ self.driver.execute_script("arguments[0].click();", element)+ except:+ element.click()+ return+ except:+ continue++ raise Exception(f'Could not find clickable element with xpath: {xpath}')++ except Exception as e:+ print(f"Failed to click element. Error: {str(e)}")+ raise Exception(f'Failed to click element with index {index}, xpath: {xpath}')def input_text_by_index(self, index: int, text: str):"""Inputs text into a field using its index from the selector map."""- if str(index) not in self.selector_map:+ if int(index) not in self.selector_map:raise Exception(f'Element index {index} not found in selector map')- xpath = self.selector_map[str(index)]- element = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))+ xpath = self.selector_map[int(index)]++ try:+ # First try: Direct XPath+ element = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))+ except:+ try:+ # Second try: Simplified XPath+ clean_xpath = xpath.replace('[document]/', '')+ if not clean_xpath.startswith('//'):+ clean_xpath = '//' + clean_xpath+ element = self.wait.until(EC.presence_of_element_located((By.XPATH, clean_xpath)))+ except:+ raise Exception(f'Failed to find input element with index {index}, xpath: {xpath}')+element.clear()element.send_keys(text)diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.pyindex 6853656f8..815cbca7f 100644--- a/src/agent_interface/planing_agent.py+++ b/src/agent_interface/planing_agent.py@@ -1,6 +1,6 @@import jsonimport os-from typing import Dict+from typing import Dict, Listfrom dotenv import load_dotenvfrom openai import OpenAIdiff --git a/src/dom/service.py b/src/dom/service.pyindex 6296b693d..ef9c88d12 100644--- a/src/dom/service.py+++ b/src/dom/service.py@@ -7,227 +7,231 @@ from pydantic import BaseModelclass ProcessedDomContent(BaseModel):- output_string: str- selector_map: dict+ output_string: str+ selector_map: dict[int, str]class DomService:- def process_content(self, html_content: str) -> ProcessedDomContent:- """- Process HTML content to extract and clean relevant elements.- Args:- html_content: Raw HTML string to process- Returns:- ProcessedDomContent: Processed DOM content- """- # Parse HTML content using BeautifulSoup- soup = BeautifulSoup(html_content, 'html.parser')-- candidate_elements: list[Tag | NavigableString] = []- dom_queue = list(soup.body.children) if soup.body else []- xpath_cache = {}-- # Find candidate elements- while dom_queue:- element = dom_queue.pop()- should_add_element = False-- # Handle both Tag elements and text nodes- if isinstance(element, Tag):- if self._is_element_accepted(element):- # Add children to queue in reverse order only if element is accepted- for child in reversed(list(element.children)):- dom_queue.append(child)-- # Check if element is interactive or leaf element- if self._is_interactive_element(element) or self._is_leaf_element(element):- should_add_element = True-- elif isinstance(element, NavigableString) and element.strip():- should_add_element = True-- if should_add_element:- if not isinstance(element, (Tag, NavigableString)):- continue- candidate_elements.append(element)-- # Process candidates- selector_map = {}- output_string = ''-- for index, element in enumerate(candidate_elements):- xpath = xpath_cache.get(element)- if not xpath:- xpath = self._generate_xpath(element)- xpath_cache[element] = xpath-- # Skip text nodes that are direct children of already processed elements- if isinstance(element, NavigableString) and element.parent in candidate_elements:- continue-- if isinstance(element, str):- text_content = element.strip()- if text_content:- output_string += f'{index}:{text_content}\n'- else:- tag_name = element.name- attributes = self._get_essential_attributes(element)-- opening_tag = f"<{tag_name}{' ' + attributes if attributes else ''}>"- closing_tag = f'</{tag_name}>'- text_content = element.get_text().strip() or ''-- output_string += f'{index}:{opening_tag}{text_content}{closing_tag}\n'-- selector_map[index] = xpath-- return ProcessedDomContent(output_string=output_string, selector_map=selector_map)-- def _is_interactive_element(self, element: Tag) -> bool:- """Check if element is interactive based on tag name and attributes."""- interactive_elements = {- 'a',- 'button',- 'details',- 'embed',- 'input',- 'label',- 'menu',- 'menuitem',- 'object',- 'select',- 'textarea',- 'summary',- }- interactive_roles = {- 'button',- 'menu',- 'menuitem',- 'link',- 'checkbox',- 'radio',- 'slider',- 'tab',- 'tabpanel',- 'textbox',- 'combobox',- 'grid',- 'listbox',- 'option',- 'progressbar',- 'scrollbar',- 'searchbox',- 'switch',- 'tree',- 'treeitem',- 'spinbutton',- 'tooltip',- }-- return (- element.name in interactive_elements- or element.get('role') in interactive_roles- or element.get('aria-role') in interactive_roles- )-- def _is_leaf_element(self, element: Tag) -> bool:- """Check if element is a leaf element."""- if not element.get_text(strip=True):- return False-- if not list(element.children):- return True-- # Check for simple text-only elements- children = list(element.children)- if len(children) == 1 and isinstance(children[0], str):- return True-- return False-- def _is_element_accepted(self, element: Tag) -> bool:- """Check if element is accepted based on tag name."""- leaf_element_deny_list = {'svg', 'iframe', 'script', 'style', 'link'}-- # First check if it's in deny list- if element.name in leaf_element_deny_list:- return False-- return element.name not in leaf_element_deny_list-- def _generate_xpath(self, element: Tag | NavigableString) -> str:- """Generate XPath for given element."""- # Handle NavigableString - return parent's xpath- if isinstance(element, NavigableString):- if element.parent:- return self._generate_xpath(element.parent)- return ''-- # Handle elements that may not have all Tag methods- if not hasattr(element, 'name'):- return ''-- # Check for ID using getattr to handle elements without get() method- element_id = getattr(element, 'get', lambda x: None)('id')- if element_id:- return f"//*[@id='{element_id}']"-- parts = []- current = element-- while current and getattr(current, 'name', None):- # Safely get parent and children- parent = getattr(current, 'parent', None)- siblings = list(parent.children) if parent and hasattr(parent, 'children') else []-- # Filter siblings that are elements with matching names- same_type_siblings = [- s for s in siblings if hasattr(s, 'name') and s.name == current.name- ]-- if len(same_type_siblings) > 1:- try:- index = same_type_siblings.index(current) + 1- parts.insert(0, f'{current.name}[{index}]')- except ValueError:- parts.insert(0, current.name)- else:- parts.insert(0, current.name)-- current = parent-- return '/' + '/'.join(parts) if parts else ''-- def _get_essential_attributes(self, element: Tag) -> str:- """- Collects essential attributes from an element.- Args:- element: The BeautifulSoup PageElement- Returns:- A string of formatted essential attributes- """- essential_attributes = [- 'id',- # 'class',- 'href',- 'src',- 'aria-label',- 'aria-name',- 'aria-role',- 'aria-description',- 'aria-expanded',- 'aria-haspopup',- ]-- # Collect essential attributes that have values- attrs = []- for attr in essential_attributes:- if attr in element.attrs:- attrs.append(f'{attr}="{element[attr]}"')-- # Collect data- attributes- # for attr in element.attrs:- # if attr.startswith('data-'):- # attrs.append(f'{attr}="{element[attr]}"')-- return ' '.join(attrs)+ def process_content(self, html_content: str) -> ProcessedDomContent:+ """+ Process HTML content to extract and clean relevant elements.+ Args:+ html_content: Raw HTML string to process+ Returns:+ ProcessedDomContent: Processed DOM content+ """+ # Parse HTML content using BeautifulSoup+ soup = BeautifulSoup(html_content, 'html.parser')++ candidate_elements: list[Tag | NavigableString] = []+ dom_queue = list(soup.body.children) if soup.body else []+ xpath_cache = {}++ # Find candidate elements+ while dom_queue:+ element = dom_queue.pop()+ should_add_element = False++ # Handle both Tag elements and text nodes+ if isinstance(element, Tag):+ if self._is_element_accepted(element):+ # Add children to queue in reverse order only if element is accepted+ for child in reversed(list(element.children)):+ dom_queue.append(child)++ # Check if element is interactive or leaf element+ if self._is_interactive_element(element) or self._is_leaf_element(element):+ should_add_element = True++ elif isinstance(element, NavigableString) and element.strip():+ should_add_element = True++ if should_add_element:+ if not isinstance(element, (Tag, NavigableString)):+ continue+ candidate_elements.append(element)++ # Process candidates+ selector_map = {}+ output_string = ''++ for index, element in enumerate(candidate_elements):+ xpath = xpath_cache.get(element)+ if not xpath:+ xpath = self._generate_xpath(element)+ xpath_cache[element] = xpath++ # Skip text nodes that are direct children of already processed elements+ if isinstance(element, NavigableString) and element.parent in candidate_elements:+ continue++ if isinstance(element, str):+ text_content = element.strip()+ if text_content:+ output_string += f'{index}:{text_content}\n'+ else:+ tag_name = element.name+ attributes = self._get_essential_attributes(element)++ opening_tag = f"<{tag_name}{' ' + attributes if attributes else ''}>"+ closing_tag = f'</{tag_name}>'+ text_content = element.get_text().strip() or ''++ output_string += f'{index}:{opening_tag}{text_content}{closing_tag}\n'++ selector_map[index] = xpath++ return ProcessedDomContent(output_string=output_string, selector_map=selector_map)++ def _is_interactive_element(self, element: Tag) -> bool:+ """Check if element is interactive based on tag name and attributes."""+ interactive_elements = {+ 'a',+ 'button',+ 'details',+ 'embed',+ 'input',+ 'label',+ 'menu',+ 'menuitem',+ 'object',+ 'select',+ 'textarea',+ 'summary',+ }+ interactive_roles = {+ 'button',+ 'menu',+ 'menuitem',+ 'link',+ 'checkbox',+ 'radio',+ 'slider',+ 'tab',+ 'tabpanel',+ 'textbox',+ 'combobox',+ 'grid',+ 'listbox',+ 'option',+ 'progressbar',+ 'scrollbar',+ 'searchbox',+ 'switch',+ 'tree',+ 'treeitem',+ 'spinbutton',+ 'tooltip',+ }++ return (+ element.name in interactive_elements+ or element.get('role') in interactive_roles+ or element.get('aria-role') in interactive_roles+ )++ def _is_leaf_element(self, element: Tag) -> bool:+ """Check if element is a leaf element."""+ if not element.get_text(strip=True):+ return False++ if not list(element.children):+ return True++ # Check for simple text-only elements+ children = list(element.children)+ if len(children) == 1 and isinstance(children[0], str):+ return True++ return False++ def _is_element_accepted(self, element: Tag) -> bool:+ """Check if element is accepted based on tag name."""+ leaf_element_deny_list = {'svg', 'iframe', 'script', 'style', 'link'}++ # First check if it's in deny list+ if element.name in leaf_element_deny_list:+ return False++ return element.name not in leaf_element_deny_list++ def _generate_xpath(self, element: Tag | NavigableString) -> str:+ """Generate XPath for given element."""+ # Handle NavigableString - return parent's xpath+ if isinstance(element, NavigableString):+ if element.parent:+ return self._generate_xpath(element.parent)+ return ''++ # Handle elements that may not have all Tag methods+ if not hasattr(element, 'name'):+ return ''++ # Check for ID+ element_id = getattr(element, 'get', lambda x: None)('id')+ if element_id:+ return f"//[@id='{element_id}']"++ parts = []+ current = element++ while current and getattr(current, 'name', None):+ # Skip document node+ if current.name == '[document]':+ current = getattr(current, 'parent', None)+ continue++ parent = getattr(current, 'parent', None)+ if parent and hasattr(parent, 'children'):+ siblings = [s for s in parent.children+ if hasattr(s, 'name') and s.name == current.name]++ if len(siblings) > 1:+ try:+ index = siblings.index(current) + 1+ parts.insert(0, f"{current.name}[{index}]")+ except ValueError:+ parts.insert(0, current.name)+ else:+ parts.insert(0, current.name)+ else:+ parts.insert(0, current.name)++ current = parent++ xpath = '//' + '/'.join(p for p in parts if p != '[document]')+ return xpath++ def _get_essential_attributes(self, element: Tag) -> str:+ """+ Collects essential attributes from an element.+ Args:+ element: The BeautifulSoup PageElement+ Returns:+ A string of formatted essential attributes+ """+ essential_attributes = [+ 'id',+ # 'class',+ 'href',+ 'src',+ 'aria-label',+ 'aria-name',+ 'aria-role',+ 'aria-description',+ 'aria-expanded',+ 'aria-haspopup',+ ]++ # Collect essential attributes that have values+ attrs = []+ for attr in essential_attributes:+ if attr in element.attrs:+ attrs.append(f'{attr}="{element[attr]}"')++ # Collect data- attributes+ # for attr in element.attrs:+ # if attr.startswith('data-'):+ # attrs.append(f'{attr}="{element[attr]}"')++ return ' '.join(attrs)diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex 53ba3d7a2..0c6fa82d7 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -25,6 +25,7 @@ class TestKayakSearch(unittest.TestCase):print(f'Default actions: {default_actions}')agent = PlaningAgent(task, default_actions)+ url_history = []# Main interaction loopmax_steps = 10@@ -37,10 +38,11 @@ class TestKayakSearch(unittest.TestCase):print(f'Current state map: {current_state["selector_map"]}')# save_markdown(current_state["main_content"], f"current_state_{i}.md")# Get next action from agent- text = f'Elements: {current_state["interactable_elements"]}'+ url_history.append(self.driver.current_url)+ text = f'Elements: {current_state["interactable_elements"]}, Url history: {url_history}'print(f'\n{text}\n')- action = agent.chat(text, skip_call=True)+ action = agent.chat(text, skip_call=False)print(f'Selected action: {action}')out = self.actions.execute_action(action, current_state['selector_map'])