Skip to content

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

tiny improvements to css selector generation

Gregor Žunič45a46f8fbd14
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index e45751a20..e661b7049 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -617,7 +617,7 @@ class BrowserContext:
def _enhanced_css_selector_for_element(self, element: DOMElementNode) -> str:
"""
- Creates a CSS selector for a DOM element, handling various edge cases and special characters.
+ Creates a CSS selector for a DOM element, prioritizing unique identifiers.
Args:
element: The DOM element to create a selector for
@@ -629,14 +629,44 @@ class BrowserContext:
# Get base selector from XPath
css_selector = self._convert_simple_xpath_to_css_selector(element.xpath)
- # Handle class attributes
+ # First priority - unique identifiers
+ UNIQUE_IDENTIFIERS = {'id', 'data-testid', 'data-id', 'data-qa', 'data-cy', 'data-test'}
+
+ # Second priority - attributes that often contain unique values
+ SEMI_UNIQUE_ATTRIBUTES = {
+ 'href',
+ 'src',
+ 'value',
+ 'name',
+ 'for',
+ 'aria-controls',
+ 'action',
+ 'data-url',
+ 'data-href',
+ }
+
+ # Third priority - descriptive attributes
+ DESCRIPTIVE_ATTRIBUTES = {
+ 'type',
+ 'role',
+ 'aria-label',
+ 'title',
+ 'placeholder',
+ 'alt',
+ 'aria-expanded',
+ 'aria-haspopup',
+ 'aria-selected',
+ 'aria-current',
+ 'aria-pressed',
+ 'autocomplete',
+ }
+
+ # Handle class attributes first (keeping original logic)
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
@@ -644,32 +674,39 @@ class BrowserContext:
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}"]'
+ # Check for unique identifiers
+ for attr in UNIQUE_IDENTIFIERS:
+ if attr in element.attributes and element.attributes[attr]:
+ value = element.attributes[attr].strip()
+ if value:
+ value = value.replace('"', '\\"')
+ return f'{css_selector}[{attr}="{value}"]'
+
+ # Then check semi-unique attributes
+ for attr in SEMI_UNIQUE_ATTRIBUTES:
+ if attr in element.attributes and element.attributes[attr]:
+ value = element.attributes[attr].strip()
+ if value and len(value) < 100: # Avoid extremely long values
+ value = value.replace('"', '\\"')
+ css_selector += f'[{attr}="{value}"]'
+ return css_selector # Return early as these are usually unique enough
+
+ # Finally, add descriptive attributes if selector isn't unique enough
+ attr_count = 0
+ for attr in DESCRIPTIVE_ATTRIBUTES:
+ if attr_count >= 2: # Limit to 2 descriptive attributes
+ break
+ if attr in element.attributes and element.attributes[attr]:
+ value = element.attributes[attr].strip()
+ if value and len(value) < 50: # Skip very long values
+ value = value.replace('"', '\\"')
+ css_selector += f'[{attr}="{value}"]'
+ attr_count += 1
return css_selector
except Exception:
- # Fallback to a more basic selector if something goes wrong
+ # Fallback to a simple but unique selector
tag_name = element.tag_name or '*'
return f"{tag_name}[highlight_index='{element.highlight_index}']"
diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.py
index 9254add61..6d9a559a8 100644
--- a/browser_use/browser/tests/test_clicks.py
+++ b/browser_use/browser/tests/test_clicks.py
@@ -19,7 +19,8 @@ async def test_highlight_elements():
# await page.goto('https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/service-plans')
# await page.goto('https://google.com/search?q=elon+musk')
# await page.goto('https://kayak.com')
- await page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe')
+ # await page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe')
+ await page.goto('https://dictionary.cambridge.org')
await asyncio.sleep(1)