Skip to content

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

formatted stuff

Gregor Žunič52722e73b978
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.py
index 9761b2348..da65c02eb 100644
--- a/src/actions/browser_actions.py
+++ b/src/actions/browser_actions.py
@@ -7,151 +7,166 @@ from selenium.webdriver.support.ui import WebDriverWait
class BrowserActions:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
- self.wait = WebDriverWait(driver, 10)
- self.selector_map = {} # Will store current selector map
-
- def update_selector_map(self, selector_map: dict):
- """Update the current selector map"""
- self.selector_map = selector_map
-
- def execute_action(self, action: dict, selector_map: dict):
- print(action.keys())
- action_name = action['action']
- self.update_selector_map(selector_map)
-
- if 'params' in action:
- params = action['params']
- else:
- params = {}
-
- if action_name == 'search_google':
- self.search_google(params['query'])
- elif action_name == 'nothing':
- pass
- elif action_name == 'go_to_url':
- self.go_to_url(params['url'])
- elif action_name == 'go_back':
- self.go_back()
- elif action_name == 'done':
- return True
- elif action_name == 'input':
- self.input_text_by_index(params['id'], params['text'])
- elif action_name == 'click':
- self.click_element_by_index(params['id'])
- # elif action_name == 'accept_cookies':
- # self.driver.accept_cookies()
- else:
- raise Exception(f'Action {action_name} not found')
-
- def click_element_by_index(self, index: int):
- """
- Clicks an element using its index from the selector map with improved element finding strategies.
- """
- 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[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 int(index) not in self.selector_map:
- raise Exception(f'Element index {index} not found in selector map')
-
- 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)
-
- # default actions
- def search_google(self, query: str):
- """
- Performs a Google search with the provided query.
- """
- # TODO: replace with search api
- self.driver.get('https://www.google.com')
-
- search_box = self.wait.until(EC.presence_of_element_located((By.NAME, 'q')))
- search_box.send_keys(query)
- search_box.submit()
-
- def go_to_url(self, url: str):
- """
- Navigates the browser to the specified URL.
- """
- self.driver.get(url)
-
- def go_back(self):
- """
- Navigates back in the browser history.
- """
- self.driver.back()
-
- def get_default_actions(self) -> dict[str, str]:
- return {
- 'search_google': 'query: string',
- 'go_to_url': 'url: string',
- 'done': '',
- 'go_back': '',
- 'click': 'id: int',
- 'input': 'id: int, text: string',
- 'nothing': '',
- }
- # 'accept_cookies': '',
+ def __init__(self, driver: webdriver.Chrome):
+ self.driver = driver
+ self.wait = WebDriverWait(driver, 10)
+ self.selector_map = {} # Will store current selector map
+
+ def update_selector_map(self, selector_map: dict):
+ """Update the current selector map"""
+ self.selector_map = selector_map
+
+ def execute_action(self, action: dict, selector_map: dict):
+ print(action.keys())
+ action_name = action['action']
+ self.update_selector_map(selector_map)
+
+ if 'params' in action:
+ params = action['params']
+ else:
+ params = {}
+
+ if action_name == 'search_google':
+ self.search_google(params['query'])
+ elif action_name == 'nothing':
+ pass
+ elif action_name == 'go_to_url':
+ self.go_to_url(params['url'])
+ elif action_name == 'go_back':
+ self.go_back()
+ elif action_name == 'done':
+ return True
+ elif action_name == 'input':
+ self.input_text_by_index(params['id'], params['text'])
+ elif action_name == 'click':
+ self.click_element_by_index(params['id'])
+ # elif action_name == 'accept_cookies':
+ # self.driver.accept_cookies()
+ else:
+ raise Exception(f'Action {action_name} not found')
+
+ def click_element_by_index(self, index: int):
+ """
+ Clicks an element using its index from the selector map with improved element finding strategies.
+ """
+ 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[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 int(index) not in self.selector_map:
+ raise Exception(f'Element index {index} not found in selector map')
+
+ 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)
+
+ # default actions
+ def search_google(self, query: str):
+ """
+ Performs a Google search with the provided query.
+ """
+ # TODO: replace with search api
+ self.driver.get('https://www.google.com')
+
+ search_box = self.wait.until(EC.presence_of_element_located((By.NAME, 'q')))
+ search_box.send_keys(query)
+ search_box.submit()
+
+ def go_to_url(self, url: str):
+ """
+ Navigates the browser to the specified URL.
+ """
+ self.driver.get(url)
+
+ def go_back(self):
+ """
+ Navigates back in the browser history.
+ """
+ self.driver.back()
+
+ def get_default_actions(self) -> dict[str, str]:
+ return {
+ 'search_google': 'query: string',
+ 'go_to_url': 'url: string',
+ 'done': '',
+ 'go_back': '',
+ 'click': 'id: int',
+ 'input': 'id: int, text: string',
+ 'nothing': '',
+ }
+ # 'accept_cookies': '',
diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.py
index 815cbca7f..ec3821401 100644
--- a/src/agent_interface/planing_agent.py
+++ b/src/agent_interface/planing_agent.py
@@ -8,59 +8,59 @@ from tokencost import calculate_prompt_cost, count_string_tokens
class PlaningAgent:
- def __init__(self, task: str, default_actions: str):
- load_dotenv()
- self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
- self.model = 'gpt-4o'
- self.messages = [
- {'role': 'system', 'content': self.get_system_prompt(task, default_actions)}
- ]
-
- def chat(self, task: str, skip_call: bool = False) -> Dict:
- # TODO: include state, actions, etc.
-
- # select next functions to call
- messages = self.messages + [{'role': 'user', 'content': task}]
-
- # Calculate total cost for all messages
- total_cost = calculate_prompt_cost(messages, self.model)
- total_tokens = count_string_tokens(' '.join([m['content'] for m in messages]), self.model)
- print(
- 'Total prompt cost: ',
- f'${total_cost:,.2f}',
- 'Total tokens: ',
- f'{total_tokens:,}',
- )
-
- if skip_call:
- return {'action': 'nothing'}
-
- response = self.client.chat.completions.create(
- model=self.model, messages=messages, response_format={'type': 'json_object'}
- )
-
- # Only append the output message
- self.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})
-
- return json.loads(response.choices[0].message.content)
-
- def get_system_prompt(self, task: str, default_actions: str) -> str:
- """
- Get the system prompt for the agent.
-
- Args:
- task: The task description
- default_actions: Available default actions
-
- Returns:
- str: Formatted system prompt
- """
- # System prompts for the agent
- output_format = """
+ def __init__(self, task: str, default_actions: str):
+ load_dotenv()
+ self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
+ self.model = 'gpt-4o'
+ self.messages = [
+ {'role': 'system', 'content': self.get_system_prompt(task, default_actions)}
+ ]
+
+ def chat(self, task: str, skip_call: bool = False) -> Dict:
+ # TODO: include state, actions, etc.
+
+ # select next functions to call
+ messages = self.messages + [{'role': 'user', 'content': task}]
+
+ # Calculate total cost for all messages
+ total_cost = calculate_prompt_cost(messages, self.model)
+ total_tokens = count_string_tokens(' '.join([m['content'] for m in messages]), self.model)
+ print(
+ 'Total prompt cost: ',
+ f'${total_cost:,.2f}',
+ 'Total tokens: ',
+ f'{total_tokens:,}',
+ )
+
+ if skip_call:
+ return {'action': 'nothing'}
+
+ response = self.client.chat.completions.create(
+ model=self.model, messages=messages, response_format={'type': 'json_object'}
+ )
+
+ # Only append the output message
+ self.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})
+
+ return json.loads(response.choices[0].message.content)
+
+ def get_system_prompt(self, task: str, default_actions: str) -> str:
+ """
+ Get the system prompt for the agent.
+
+ Args:
+ task: The task description
+ default_actions: Available default actions
+
+ Returns:
+ str: Formatted system prompt
+ """
+ # System prompts for the agent
+ output_format = """
{"action": "action_name", "params": {"param_name": "param_value"}}
"""
- AGENT_PROMPT = f"""
+ AGENT_PROMPT = f"""
You are an AI agent that helps users navigate websites and perform actions. Your task is: {task}
Available actions:
@@ -82,10 +82,10 @@ class PlaningAgent:
"""
- return AGENT_PROMPT
+ return AGENT_PROMPT
- # Remember:
- # 1. Always check if elements exist before trying to interact with them
- # 2. Use the exact index numbers shown in the elements list
- # 3. If you need to accept cookies, use the accept_cookies action first
- # 4. If you can't find what you're looking for, consider scrolling or navigating to a different page
+ # Remember:
+ # 1. Always check if elements exist before trying to interact with them
+ # 2. Use the exact index numbers shown in the elements list
+ # 3. If you need to accept cookies, use the accept_cookies action first
+ # 4. If you can't find what you're looking for, consider scrolling or navigating to a different page
diff --git a/src/dom/service.py b/src/dom/service.py
index 2d5d837ce..727f1fe36 100644
--- a/src/dom/service.py
+++ b/src/dom/service.py
@@ -8,267 +8,267 @@ from selenium import webdriver
class ProcessedDomContent(BaseModel):
- output_string: str
- selector_map: dict
+ output_string: str
+ selector_map: dict
class DomService:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
-
- def get_current_state(self) -> ProcessedDomContent:
- html_content = self.driver.page_source
- return self._process_content(html_content)
-
- 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):
- if (
- self._is_active(element)
- and self._is_top_element(element)
- and self._is_visible(element)
- ):
- should_add_element = True
-
- elif isinstance(element, NavigableString) and element.strip():
- if self._is_visible(element):
- 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):
- # Skip document node
- if current.name == '[document]':
- break
-
- # 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
-
- # Ensure we start with html and body tags for a complete path
- if parts and parts[0] != 'html':
- parts.insert(0, 'html')
- if len(parts) > 1 and parts[1] != 'body':
- parts.insert(1, 'body')
-
- 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 _is_visible(self, element: Tag | NavigableString) -> bool:
- """Check if element is visible using JavaScript."""
- if not isinstance(element, Tag):
- return self._is_text_visible(element)
-
- element_id = element.get('id', '')
- if element_id:
- js_selector = f'document.getElementById("{element_id}")'
- else:
- xpath = self._generate_xpath(element)
- js_selector = f'document.evaluate("{xpath}", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue'
-
- visibility_check = f"""
+ def __init__(self, driver: webdriver.Chrome):
+ self.driver = driver
+
+ def get_current_state(self) -> ProcessedDomContent:
+ html_content = self.driver.page_source
+ return self._process_content(html_content)
+
+ 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):
+ if (
+ self._is_active(element)
+ and self._is_top_element(element)
+ and self._is_visible(element)
+ ):
+ should_add_element = True
+
+ elif isinstance(element, NavigableString) and element.strip():
+ if self._is_visible(element):
+ 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):
+ # Skip document node
+ if current.name == '[document]':
+ break
+
+ # 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
+
+ # Ensure we start with html and body tags for a complete path
+ if parts and parts[0] != 'html':
+ parts.insert(0, 'html')
+ if len(parts) > 1 and parts[1] != 'body':
+ parts.insert(1, 'body')
+
+ 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 _is_visible(self, element: Tag | NavigableString) -> bool:
+ """Check if element is visible using JavaScript."""
+ if not isinstance(element, Tag):
+ return self._is_text_visible(element)
+
+ element_id = element.get('id', '')
+ if element_id:
+ js_selector = f'document.getElementById("{element_id}")'
+ else:
+ xpath = self._generate_xpath(element)
+ js_selector = f'document.evaluate("{xpath}", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue'
+
+ visibility_check = f"""
return (function() {{
const element = {js_selector};
@@ -284,20 +284,20 @@ class DomService:
}}());
"""
- try:
- is_visible = self.driver.execute_script(visibility_check)
- return bool(is_visible)
- except Exception:
- return False
+ try:
+ is_visible = self.driver.execute_script(visibility_check)
+ return bool(is_visible)
+ except Exception:
+ return False
- def _is_text_visible(self, element: NavigableString) -> bool:
- """Check if text node is visible using JavaScript."""
- parent = element.parent
- if not parent:
- return False
+ def _is_text_visible(self, element: NavigableString) -> bool:
+ """Check if text node is visible using JavaScript."""
+ parent = element.parent
+ if not parent:
+ return False
- xpath = self._generate_xpath(parent)
- visibility_check = f"""
+ xpath = self._generate_xpath(parent)
+ visibility_check = f"""
return (function() {{
const parent = document.evaluate("{xpath}", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
@@ -322,16 +322,16 @@ class DomService:
}}));
}}());
"""
- try:
- is_visible = self.driver.execute_script(visibility_check)
- return bool(is_visible)
- except Exception:
- return False
-
- def _is_top_element(self, element: Tag | NavigableString, rect=None) -> bool:
- """Check if element is the topmost at its position."""
- xpath = self._generate_xpath(element)
- check_top = f"""
+ try:
+ is_visible = self.driver.execute_script(visibility_check)
+ return bool(is_visible)
+ except Exception:
+ return False
+
+ def _is_top_element(self, element: Tag | NavigableString, rect=None) -> bool:
+ """Check if element is the topmost at its position."""
+ xpath = self._generate_xpath(element)
+ check_top = f"""
return (function() {{
const elem = document.evaluate("{xpath}", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!elem) {{
@@ -358,16 +358,16 @@ class DomService:
}}));
}}());
"""
- try:
- is_top = self.driver.execute_script(check_top)
- return bool(is_top)
- except Exception:
- return False
-
- def _is_active(self, element: Tag) -> bool:
- """Check if element is active (not disabled)."""
- return not (
- element.get('disabled') is not None
- or element.get('hidden') is not None
- or element.get('aria-disabled') == 'true'
- )
+ try:
+ is_top = self.driver.execute_script(check_top)
+ return bool(is_top)
+ except Exception:
+ return False
+
+ def _is_active(self, element: Tag) -> bool:
+ """Check if element is active (not disabled)."""
+ return not (
+ element.get('disabled') is not None
+ or element.get('hidden') is not None
+ or element.get('aria-disabled') == 'true'
+ )
diff --git a/src/utils/selenium_utils.py b/src/utils/selenium_utils.py
index 672098807..60ee09700 100644
--- a/src/utils/selenium_utils.py
+++ b/src/utils/selenium_utils.py
@@ -8,100 +8,100 @@ from webdriver_manager.chrome import ChromeDriverManager
def setup_selenium_driver(headless: bool = False) -> webdriver.Chrome:
- """
- Sets up and returns a Selenium WebDriver instance.
+ """
+ Sets up and returns a Selenium WebDriver instance.
- Args:
- headless (bool): Whether to run browser in headless mode
+ Args:
+ headless (bool): Whether to run browser in headless mode
- Returns:
- webdriver.Chrome: Configured Chrome WebDriver instance
- """
- # Configure Chrome options
- chrome_options = Options()
- if headless:
- chrome_options.add_argument('--headless')
+ Returns:
+ webdriver.Chrome: Configured Chrome WebDriver instance
+ """
+ # Configure Chrome options
+ chrome_options = Options()
+ if headless:
+ chrome_options.add_argument('--headless')
- # Disable automation flags
- chrome_options.add_argument('--disable-blink-features=AutomationControlled')
- chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
- chrome_options.add_experimental_option('useAutomationExtension', False)
+ # Disable automation flags
+ chrome_options.add_argument('--disable-blink-features=AutomationControlled')
+ chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
+ chrome_options.add_experimental_option('useAutomationExtension', False)
- # Initialize the Chrome driver
- driver = webdriver.Chrome(
- service=Service(ChromeDriverManager().install()), options=chrome_options
- )
+ # Initialize the Chrome driver
+ driver = webdriver.Chrome(
+ service=Service(ChromeDriverManager().install()), options=chrome_options
+ )
- # Add cookie acceptance function
- def accept_cookies(driver):
- """
- More robust cookie acceptance function that tries multiple approaches
- """
- try:
- # Common cookie accept button selectors
- cookie_selectors = [
- "button[id*='cookie-accept']",
- "button[id*='accept-cookie']",
- "button[class*='cookie-accept']",
- "button[class*='accept-cookie']",
- "[aria-label*='accept' i][role='button']",
- "[aria-label*='cookie' i][role='button']",
- "button:contains('Accept')",
- "button:contains('Akzeptieren')",
- "button:contains('Zustimmen')",
- "button:contains('Alle akzeptieren')",
- '#onetrust-accept-btn-handler',
- '#accept-all-cookies',
- '.accept-cookies',
- '.accept-all-cookies',
- ]
+ # Add cookie acceptance function
+ def accept_cookies(driver):
+ """
+ More robust cookie acceptance function that tries multiple approaches
+ """
+ try:
+ # Common cookie accept button selectors
+ cookie_selectors = [
+ "button[id*='cookie-accept']",
+ "button[id*='accept-cookie']",
+ "button[class*='cookie-accept']",
+ "button[class*='accept-cookie']",
+ "[aria-label*='accept' i][role='button']",
+ "[aria-label*='cookie' i][role='button']",
+ "button:contains('Accept')",
+ "button:contains('Akzeptieren')",
+ "button:contains('Zustimmen')",
+ "button:contains('Alle akzeptieren')",
+ '#onetrust-accept-btn-handler',
+ '#accept-all-cookies',
+ '.accept-cookies',
+ '.accept-all-cookies',
+ ]
- wait = WebDriverWait(driver, 10)
+ wait = WebDriverWait(driver, 10)
- # Try each selector
- for selector in cookie_selectors:
- try:
- # Try to find element by CSS selector
- cookie_button = wait.until(
- EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
- )
- cookie_button.click()
- return True
- except:
- try:
- # Try to find element by XPath containing text
- xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{selector.lower()}')]"
- cookie_button = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
- cookie_button.click()
- return True
- except:
- continue
+ # Try each selector
+ for selector in cookie_selectors:
+ try:
+ # Try to find element by CSS selector
+ cookie_button = wait.until(
+ EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
+ )
+ cookie_button.click()
+ return True
+ except:
+ try:
+ # Try to find element by XPath containing text
+ xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{selector.lower()}')]"
+ cookie_button = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
+ cookie_button.click()
+ return True
+ except:
+ continue
- # Try finding iframe with cookie consent
- iframes = driver.find_elements(By.TAG_NAME, 'iframe')
- for iframe in iframes:
- try:
- driver.switch_to.frame(iframe)
- for selector in cookie_selectors:
- try:
- cookie_button = wait.until(
- EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
- )
- cookie_button.click()
- driver.switch_to.default_content()
- return True
- except:
- continue
- driver.switch_to.default_content()
- except:
- driver.switch_to.default_content()
- continue
+ # Try finding iframe with cookie consent
+ iframes = driver.find_elements(By.TAG_NAME, 'iframe')
+ for iframe in iframes:
+ try:
+ driver.switch_to.frame(iframe)
+ for selector in cookie_selectors:
+ try:
+ cookie_button = wait.until(
+ EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
+ )
+ cookie_button.click()
+ driver.switch_to.default_content()
+ return True
+ except:
+ continue
+ driver.switch_to.default_content()
+ except:
+ driver.switch_to.default_content()
+ continue
- except Exception as e:
- print(f'Error accepting cookies: {str(e)}')
- return False
+ except Exception as e:
+ print(f'Error accepting cookies: {str(e)}')
+ return False
- # Attach the function to the driver instance
- driver.accept_cookies = lambda: accept_cookies(driver)
+ # Attach the function to the driver instance
+ driver.accept_cookies = lambda: accept_cookies(driver)
- return driver
+ return driver