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
make css selectors more robust
Gregor Žunič34bb36d6f53c
diff --git a/browser_use/browser/service.py b/browser_use/browser/service.pyindex bf4122e66..73206d6de 100644--- a/browser_use/browser/service.py+++ b/browser_use/browser/service.py@@ -373,44 +373,109 @@ class Browser:# region - User Actionsdef _convert_simple_xpath_to_css_selector(self, xpath: str) -> str:- """Converts simple XPath expressions to CSS selectors.- Only handles basic XPath patterns like tag names, indices, and attributes.- """+ """Converts simple XPath expressions to CSS selectors."""+ if not xpath:+ return ''+# Remove leading slash if presentxpath = xpath.lstrip('/')# Split into partsparts = xpath.split('/')-css_parts = []+for part in parts:if not part:continue# Handle index notation [n]if '[' in part:- tag = part[: part.find('[')]- index = int(part[part.find('[') + 1 : part.find(']')]) - 1- css_parts.append(f'{tag}:nth-of-type({index+1})')+ base_part = part[: part.find('[')]+ index_part = part[part.find('[') :]++ # Handle multiple indices+ indices = [i.strip('[]') for i in index_part.split(']')[:-1]]++ for idx in indices:+ try:+ # Handle numeric indices+ if idx.isdigit():+ index = int(idx) - 1+ base_part += f':nth-of-type({index+1})'+ # Handle last() function+ elif idx == 'last()':+ base_part += ':last-of-type'+ # Handle position() functions+ elif 'position()' in idx:+ if '>1' in idx:+ base_part += ':nth-of-type(n+2)'+ except ValueError:+ continue++ css_parts.append(base_part)else:css_parts.append(part)- return ' > '.join(css_parts)+ base_selector = ' > '.join(css_parts)+ return base_selectordef _enhanced_css_selector_for_element(self, element: DOMElementNode) -> str:- css_selector = self._convert_simple_xpath_to_css_selector(element.xpath)+ """+ Creates a CSS selector for a DOM element, handling various edge cases and special characters.- # Handle class attributes first- if 'class' in element.attributes:- classes = element.attributes['class'].split()- css_selector += '.' + '.'.join(classes)+ Args:+ element: The DOM element to create a selector for- # Then add all other attribute selectors- for attribute, value in element.attributes.items():- if attribute != 'class': # Skip class since we already handled it- css_selector += f'[{attribute}="{value}"]'+ Returns:+ A valid CSS selector string+ """+ try:+ # Get base selector from XPath+ css_selector = self._convert_simple_xpath_to_css_selector(element.xpath)++ # Handle class attributes+ if 'class' in element.attributes and element.attributes['class']:+ classes = element.attributes['class'].split()+ for class_name in classes:+ # Skip empty class names+ if not class_name:+ continue++ # Escape special characters in class names+ if any(char in class_name for char in ':()[],>+~|.# '):+ # Use attribute contains for special characters+ css_selector += f'[class*="{class_name}"]'+ else:+ css_selector += f'.{class_name}'++ # Handle other attributes+ for attribute, value in element.attributes.items():+ if attribute == 'class':+ continue++ # Skip invalid attribute names+ if not attribute.strip():+ continue++ # Escape special characters in attribute names+ safe_attribute = attribute.replace(':', r'\:')++ # Handle different value cases+ if value == '':+ css_selector += f'[{safe_attribute}]'+ elif any(char in value for char in '"\'<>`'):+ # Use contains for values with special characters+ safe_value = value.replace('"', '\\"')+ css_selector += f'[{safe_attribute}*="{safe_value}"]'+ else:+ css_selector += f'[{safe_attribute}="{value}"]'++ return css_selector- return css_selector+ except Exception:+ # Fallback to a more basic selector if something goes wrong+ tag_name = element.tag_name or '*'+ return f"{tag_name}[highlight_index='{element.highlight_index}']"async def get_locate_element(self, element: DOMElementNode):current_frame = await self.get_current_page()diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.pyindex 3c66205d9..eb23a0c04 100644--- a/browser_use/browser/tests/test_clicks.py+++ b/browser_use/browser/tests/test_clicks.py@@ -38,9 +38,6 @@ async def test_highlight_elements():# browser.highlight_selector_map_elements# )(state.selector_map)- # print(state.dom_items_to_string(use_tabs=False))- # print(state.selector_map)-# Find and print duplicate XPathsxpath_counts = {}for selector in state.selector_map.values():@@ -57,7 +54,7 @@ async def test_highlight_elements():print(f'Count: {count}\n')print(state.selector_map.keys(), 'Selector map keys')- print(state.element_tree.clickable_elements_to_string(use_tabs=False))+ print(state.element_tree.clickable_elements_to_string())action = input('Select next action: ')await time_execution_sync('remove_highlight_elements')(browser.remove_highlights)()diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.pyindex c65dc3e30..de7044dd9 100644--- a/browser_use/dom/tests/extraction_test.py+++ b/browser_use/dom/tests/extraction_test.py@@ -32,7 +32,7 @@ async def test_process_html_file():elements = dom_state.element_treeselector_map = dom_state.selector_map- print(elements.clickable_elements_to_string(use_tabs=False))+ print(elements.clickable_elements_to_string())print('Tokens:', count_string_tokens(elements.clickable_elements_to_string(), model='gpt-4o'))print(len(selector_map.keys()), 'elements highlighted')diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 53895b79a..e5e0607bb 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -88,18 +88,16 @@ class DOMElementNode(DOMBaseNode):collect_text(self)return '\n'.join(text_parts).strip()- def clickable_elements_to_string(self, use_tabs: bool = True) -> str:+ def clickable_elements_to_string(self) -> str:"""Convert the processed DOM content to HTML."""formatted_text = []def process_node(node: DOMBaseNode, depth: int) -> None:- indent = '\t' * depth if use_tabs else ''-if isinstance(node, DOMElementNode):# Add element with highlight_indexif node.highlight_index is not None:formatted_text.append(- f'{node.highlight_index}[:]{indent}<{node.tag_name}>{node.get_all_text_till_next_clickable_element()}</{node.tag_name}>'+ f'{node.highlight_index}[:]<{node.tag_name}>{node.get_all_text_till_next_clickable_element()}</{node.tag_name}>')# Process children regardless@@ -109,7 +107,7 @@ class DOMElementNode(DOMBaseNode):elif isinstance(node, DOMTextNode):# Add text only if it doesn't have a highlighted parentif not node.has_parent_with_highlight_index():- formatted_text.append(f'_[:]{indent}{node.text}')+ formatted_text.append(f'_[:]{node.text}')process_node(self, 0)return '\n'.join(formatted_text)diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.pyindex bc2ccfbc2..464c55f40 100644--- a/tests/test_agent_actions.py+++ b/tests/test_agent_actions.py@@ -1,7 +1,7 @@import osimport pytest-from langchain_openai import AzureChatOpenAI, ChatOpenAI+from langchain_openai import AzureChatOpenAIfrom pydantic import BaseModel, SecretStrfrom browser_use.agent.service import Agent@@ -95,7 +95,7 @@ async def test_error_recovery(llm, agent_with_controller):assert 'url' in action['go_to_url'], 'url is not in go_to_url'assert action['go_to_url']['url'].endswith('google.com'- ), f'url does not end with google.com'+ ), 'url does not end with google.com'break@@ -192,8 +192,8 @@ async def test_captcha_solver(llm, agent_with_controller, captcha: CaptchaTest):# Verify the agent solved the captchasolved = Falsefor h in history.history:- last = h.state.items- if any(captcha.success_text in item.text for item in last):+ last = h.state.element_tree.get_all_text_till_next_clickable_element()+ if any(captcha.success_text in item for item in last):solved = Truebreakassert solved, f'Failed to solve {captcha.name}'diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.pyindex b7dc76114..34f1517f6 100644--- a/tests/test_core_functionality.py+++ b/tests/test_core_functionality.py@@ -1,7 +1,7 @@import osimport pytest-from langchain_openai import AzureChatOpenAI, ChatOpenAI+from langchain_openai import AzureChatOpenAIfrom pydantic import SecretStrfrom browser_use.agent.service import Agent