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
simple highlights
Gregor Žunič5cce5af22289
diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.pynew file mode 100644index 000000000..ed37fdafa--- /dev/null+++ b/browser_use/dom/debug/highlights.py@@ -0,0 +1,429 @@+# 100% vibe coded++import json+import traceback++from browser_use.browser.session import BrowserSession+from browser_use.dom.views import DOMSelectorMap+++def analyze_element_interactivity(element: dict) -> dict:+ """Analyze why an element is considered interactive and assign confidence level."""+ element_type = element['element_name'].lower()+ attributes = element.get('attributes', {})++ # Default reasoning structure+ reasoning = {'confidence': 'LOW', 'primary_reason': 'unknown', 'element_type': element_type, 'reasons': []}++ # High confidence elements+ if element_type in ['button', 'a', 'input', 'select', 'textarea']:+ reasoning['confidence'] = 'HIGH'+ reasoning['primary_reason'] = 'semantic_element'+ reasoning['reasons'].append(f'Semantic interactive element: {element_type}')++ # Check for interactive attributes+ interactive_attrs = ['onclick', 'onchange', 'href', 'type', 'role']+ found_attrs = [attr for attr in interactive_attrs if attr in attributes]+ if found_attrs:+ if reasoning['confidence'] != 'HIGH':+ reasoning['confidence'] = 'HIGH' if element_type in ['button', 'a'] else 'MEDIUM'+ reasoning['primary_reason'] = 'interactive_attributes'+ reasoning['reasons'].append(f'Interactive attributes: {", ".join(found_attrs)}')++ # Check for ARIA roles+ role = attributes.get('role', '').lower()+ if role in ['button', 'link', 'checkbox', 'radio', 'menuitem', 'tab']:+ reasoning['confidence'] = 'HIGH'+ reasoning['primary_reason'] = 'aria_role'+ reasoning['reasons'].append(f'Interactive ARIA role: {role}')++ # Check if marked as clickable from snapshot+ if element.get('is_clickable'):+ if reasoning['confidence'] == 'LOW':+ reasoning['confidence'] = 'MEDIUM'+ reasoning['reasons'].append('Marked as clickable in DOM snapshot')++ # Check for valid bounding box+ if element.get('width', 0) > 0 and element.get('height', 0) > 0:+ reasoning['reasons'].append(f'Valid bounding box: {element["width"]}x{element["height"]}')+ else:+ reasoning['confidence'] = 'LOW'+ reasoning['reasons'].append('Invalid or missing bounding box')++ # Fallback reasoning+ if not reasoning['reasons']:+ reasoning['reasons'].append('Element found in selector map')+ reasoning['primary_reason'] = 'selector_mapped'++ return reasoning+++def convert_dom_selector_map_to_highlight_format(selector_map: DOMSelectorMap) -> list[dict]:+ """Convert DOMSelectorMap to the format expected by the highlighting script."""+ elements = []++ for interactive_index, node in selector_map.items():+ # Get bounding box from snapshot_node if available (adapted from working implementation)+ bbox = None+ if node.snapshot_node:+ # Try bounds first, then clientRects+ rect = node.snapshot_node.bounds or node.snapshot_node.clientRects+ if rect:+ bbox = {'x': rect.x / 2, 'y': rect.y / 2, 'width': rect.width / 2, 'height': rect.height / 2}++ # Only include elements with valid bounding boxes (following working implementation)+ if bbox and bbox.get('width', 0) > 0 and bbox.get('height', 0) > 0:+ element = {+ 'x': bbox['x'],+ 'y': bbox['y'],+ 'width': bbox['width'],+ 'height': bbox['height'],+ 'interactive_index': interactive_index,+ 'element_name': node.node_name,+ 'is_clickable': node.snapshot_node.is_clickable if node.snapshot_node else True,+ 'is_scrollable': getattr(node, 'is_scrollable', False),+ 'attributes': node.attributes or {},+ 'frame_id': getattr(node, 'frame_id', None),+ 'node_id': node.node_id,+ 'backend_node_id': node.backend_node_id,+ 'xpath': node.xpath,+ 'text_content': node.get_all_children_text()[:50]+ if hasattr(node, 'get_all_children_text')+ else node.node_value[:50],+ }++ # Analyze why this element is interactive+ reasoning = analyze_element_interactivity(element)+ element['reasoning'] = reasoning++ elements.append(element)+ else:+ # Handle elements without valid bounding boxes (fallback for highlighting)+ # print(f'⚠️ Element {interactive_index} ({node.node_name}) has no valid bounding box, using fallback positioning')+ # element = {+ # 'x': 0,+ # 'y': 0,+ # 'width': 50,+ # 'height': 20,+ # 'interactive_index': interactive_index,+ # 'element_name': node.node_name,+ # 'is_clickable': node.snapshot_node.is_clickable if node.snapshot_node else True,+ # 'is_scrollable': getattr(node, 'is_scrollable', False),+ # 'attributes': node.attributes or {},+ # 'frame_id': getattr(node, 'frame_id', None),+ # 'node_id': node.node_id,+ # 'backend_node_id': node.backend_node_id,+ # 'xpath': node.xpath,+ # 'text_content': node.get_all_children_text()[:50]+ # if hasattr(node, 'get_all_children_text')+ # else node.node_value[:50],+ # }++ # Analyze why this element is interactive (with low confidence due to missing bbox)+ reasoning = analyze_element_interactivity(element)+ reasoning['confidence'] = 'LOW'+ reasoning['reasons'].append('Missing valid bounding box')+ element['reasoning'] = reasoning++ elements.append(element)++ return elements+++async def remove_highlighting_script(browser_session: BrowserSession) -> None:+ """Remove all browser-use highlighting elements from the page."""+ try:+ # Get the current page from the browser session+ page = await browser_session.get_current_page()++ print('🧹 Removing browser-use highlighting elements')++ # Create script to remove all highlights+ script = """+ (function() {+ // Remove any existing highlights+ const existingHighlights = document.querySelectorAll('[data-browser-use-highlight]');+ console.log('Removing', existingHighlights.length, 'browser-use highlight elements');+ existingHighlights.forEach(el => el.remove());+ })();+ """++ # Execute the removal script+ await page.evaluate(script)+ print('✅ All browser-use highlighting elements removed')++ except Exception as e:+ print(f'❌ Error removing highlighting elements: {e}')+ traceback.print_exc()+++async def inject_highlighting_script(browser_session: BrowserSession, interactive_elements: DOMSelectorMap) -> None:+ """Inject JavaScript to highlight interactive elements with detailed hover tooltips that work around CSP restrictions."""+ if not interactive_elements:+ print('⚠️ No interactive elements to highlight')+ return++ try:+ # Convert DOMSelectorMap to the format expected by the JavaScript+ converted_elements = convert_dom_selector_map_to_highlight_format(interactive_elements)++ # Get the current page from the browser session+ page = await browser_session.get_current_page()++ print(f'📍 Creating CSP-safe highlighting for {len(converted_elements)} elements')++ # Remove any existing highlights first+ await remove_highlighting_script(browser_session)++ # Create CSP-safe highlighting script using DOM methods instead of innerHTML+ script = f"""+ (function() {{+ // Interactive elements data with reasoning+ const interactiveElements = {json.dumps(converted_elements)};++ console.log('=== BROWSER-USE HIGHLIGHTING ===');+ console.log('Highlighting', interactiveElements.length, 'interactive elements');++ // Create container for all highlights+ const container = document.createElement('div');+ container.id = 'browser-use-debug-highlights';+ container.setAttribute('data-browser-use-highlight', 'container');+ container.style.cssText = `+ position: absolute;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ pointer-events: none;+ z-index: 999999;+ `;++ // Helper function to create text nodes safely (CSP-friendly)+ function createTextElement(tag, text, styles) {{+ const element = document.createElement(tag);+ element.textContent = text;+ if (styles) element.style.cssText = styles;+ return element;+ }}++ // Add enhanced highlights with detailed tooltips+ interactiveElements.forEach((element, index) => {{+ const highlight = document.createElement('div');+ highlight.setAttribute('data-browser-use-highlight', 'element');+ highlight.setAttribute('data-element-id', element.interactive_index);+ highlight.style.cssText = `+ position: absolute;+ left: ${{element.x}}px;+ top: ${{element.y}}px;+ width: ${{element.width}}px;+ height: ${{element.height}}px;+ border: 2px solid #4a90e2;+ background-color: rgba(74, 144, 226, 0.1);+ pointer-events: none;+ box-sizing: border-box;+ transition: all 0.2s ease;+ `;++ // Enhanced label with interactive index+ const label = createTextElement('div', element.interactive_index, `+ position: absolute;+ top: -20px;+ left: 0;+ background-color: #4a90e2;+ color: white;+ padding: 2px 6px;+ font-size: 11px;+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;+ font-weight: bold;+ border-radius: 3px;+ white-space: nowrap;+ z-index: 1000001;+ box-shadow: 0 2px 4px rgba(0,0,0,0.3);+ `);++ // Enhanced tooltip with detailed reasoning (CSP-safe)+ const tooltip = document.createElement('div');+ tooltip.setAttribute('data-browser-use-highlight', 'tooltip');+ tooltip.style.cssText = `+ position: absolute;+ top: -160px;+ left: 50%;+ transform: translateX(-50%);+ background-color: rgba(0, 0, 0, 0.95);+ color: white;+ padding: 12px 16px;+ font-size: 12px;+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;+ border-radius: 8px;+ white-space: nowrap;+ z-index: 1000002;+ opacity: 0;+ visibility: hidden;+ transition: all 0.3s ease;+ box-shadow: 0 6px 20px rgba(0,0,0,0.5);+ border: 1px solid #666;+ max-width: 400px;+ white-space: normal;+ line-height: 1.4;+ min-width: 200px;+ `;++ // Build detailed tooltip content with reasoning (CSP-safe DOM creation)+ const reasoning = element.reasoning || {{}};+ const confidence = reasoning.confidence || 'UNKNOWN';+ const primaryReason = reasoning.primary_reason || 'unknown';+ const reasons = reasoning.reasons || [];+ const elementType = reasoning.element_type || element.element_name || 'UNKNOWN';++ // Determine confidence color and styling+ let confidenceColor = '#4a90e2';+ let confidenceIcon = '🔍';+ let borderColor = '#4a90e2';++ if (confidence === 'HIGH') {{+ confidenceColor = '#28a745';+ confidenceIcon = '✅';+ borderColor = '#28a745';+ }} else if (confidence === 'MEDIUM') {{+ confidenceColor = '#ffc107';+ confidenceIcon = '⚠️';+ borderColor = '#ffc107';+ }} else {{+ confidenceColor = '#fd7e14';+ confidenceIcon = '❓';+ borderColor = '#fd7e14';+ }}++ // Create tooltip header+ const header = createTextElement('div', `${{confidenceIcon}} [${{element.interactive_index}}] ${{elementType.toUpperCase()}}`, `+ color: ${{confidenceColor}};+ font-weight: bold;+ font-size: 13px;+ margin-bottom: 8px;+ border-bottom: 1px solid #666;+ padding-bottom: 4px;+ `);++ // Create confidence indicator+ const confidenceDiv = createTextElement('div', `${{confidence}} CONFIDENCE`, `+ color: ${{confidenceColor}};+ font-size: 11px;+ font-weight: bold;+ margin-bottom: 8px;+ `);++ // Create primary reason+ const primaryReasonDiv = createTextElement('div', `Primary: ${{primaryReason.replace('_', ' ').toUpperCase()}}`, `+ color: #fff;+ font-size: 11px;+ margin-bottom: 6px;+ font-weight: bold;+ `);++ // Create reasons list+ const reasonsContainer = document.createElement('div');+ reasonsContainer.style.cssText = `+ font-size: 10px;+ color: #ccc;+ margin-top: 4px;+ `;++ if (reasons.length > 0) {{+ const reasonsTitle = createTextElement('div', 'Evidence:', `+ color: #fff;+ font-size: 10px;+ margin-bottom: 4px;+ font-weight: bold;+ `);+ reasonsContainer.appendChild(reasonsTitle);++ reasons.slice(0, 4).forEach(reason => {{+ const reasonDiv = createTextElement('div', `• ${{reason}}`, `+ color: #ccc;+ font-size: 10px;+ margin-bottom: 2px;+ padding-left: 4px;+ `);+ reasonsContainer.appendChild(reasonDiv);+ }});++ if (reasons.length > 4) {{+ const moreDiv = createTextElement('div', `... and ${{reasons.length - 4}} more`, `+ color: #999;+ font-size: 9px;+ font-style: italic;+ margin-top: 2px;+ `);+ reasonsContainer.appendChild(moreDiv);+ }}+ }} else {{+ const noReasonsDiv = createTextElement('div', 'No specific evidence found', `+ color: #999;+ font-size: 10px;+ font-style: italic;+ `);+ reasonsContainer.appendChild(noReasonsDiv);+ }}++ // Add bounding box info+ const boundsDiv = createTextElement('div', `Position: (${{Math.round(element.x)}}, ${{Math.round(element.y)}}) Size: ${{Math.round(element.width)}}×${{Math.round(element.height)}}`, `+ color: #888;+ font-size: 9px;+ margin-top: 8px;+ border-top: 1px solid #444;+ padding-top: 4px;+ `);++ // Assemble tooltip+ tooltip.appendChild(header);+ tooltip.appendChild(confidenceDiv);+ tooltip.appendChild(primaryReasonDiv);+ tooltip.appendChild(reasonsContainer);+ tooltip.appendChild(boundsDiv);++ // Set highlight border color based on confidence+ highlight.style.borderColor = borderColor;+ label.style.backgroundColor = borderColor;++ // Add hover effects+ highlight.addEventListener('mouseenter', () => {{+ highlight.style.borderColor = '#ff6b6b';+ highlight.style.backgroundColor = 'rgba(255, 107, 107, 0.2)';+ highlight.style.borderWidth = '3px';+ highlight.style.boxShadow = '0 0 10px rgba(255, 107, 107, 0.5)';+ tooltip.style.opacity = '1';+ tooltip.style.visibility = 'visible';+ label.style.backgroundColor = '#ff6b6b';+ label.style.transform = 'scale(1.1)';+ }});++ highlight.addEventListener('mouseleave', () => {{+ highlight.style.borderColor = borderColor;+ highlight.style.backgroundColor = 'rgba(74, 144, 226, 0.1)';+ highlight.style.borderWidth = '2px';+ highlight.style.boxShadow = 'none';+ tooltip.style.opacity = '0';+ tooltip.style.visibility = 'hidden';+ label.style.backgroundColor = borderColor;+ label.style.transform = 'scale(1)';+ }});++ highlight.appendChild(tooltip);+ highlight.appendChild(label);+ container.appendChild(highlight);+ }});++ // Add container to document+ document.body.appendChild(container);++ console.log('✅ Browser-use highlighting complete');+ }})();+ """++ # Inject the enhanced CSP-safe script+ await page.evaluate(script)+ print(f'✅ Enhanced CSP-safe highlighting injected for {len(converted_elements)} elements')++ except Exception as e:+ print(f'❌ Error injecting enhanced highlighting script: {e}')+ traceback.print_exc()diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.pynew file mode 100644index 000000000..609dc0eda--- /dev/null+++ b/browser_use/dom/playground/extraction.py@@ -0,0 +1,196 @@+import asyncio+import json+import os+import time++import anyio+import pyperclip+import tiktoken++from browser_use.agent.prompts import AgentMessagePrompt+from browser_use.browser import BrowserProfile, BrowserSession+from browser_use.browser.types import ViewportSize+from browser_use.dom.debug.highlights import inject_highlighting_script, remove_highlighting_script+from browser_use.dom.service import DomService+from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES+from browser_use.filesystem.file_system import FileSystem++TIMEOUT = 60+++async def test_focus_vs_all_elements():+ # async with async_patchright() as patchright:+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ # executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ window_size=ViewportSize(width=1100, height=1000),+ disable_security=True,+ wait_for_network_idle_page_load_time=1,+ headless=False,+ ),+ )++ websites = [+ # 'https://demos.telerik.com/kendo-react-ui/treeview/overview/basic/func?theme=default-ocean-blue-a11y',+ 'https://google.com',+ 'https://www.ycombinator.com/companies',+ 'https://kayak.com/flights',+ # 'https://en.wikipedia.org/wiki/Humanist_Party_of_Ontario',+ # 'https://www.google.com/travel/flights?tfs=CBwQARoJagcIARIDTEpVGglyBwgBEgNMSlVAAUgBcAGCAQsI____________AZgBAQ&tfu=KgIIAw&hl=en-US&gl=US',+ # # 'https://www.concur.com/?&cookie_preferences=cpra',+ # 'https://immobilienscout24.de',+ 'https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit',+ 'https://www.zeiss.com/career/en/job-search.html?page=1',+ 'https://www.mlb.com/yankees/stats/',+ 'https://www.amazon.com/s?k=laptop&s=review-rank&crid=1RZCEJ289EUSI&qid=1740202453&sprefix=laptop%2Caps%2C166&ref=sr_st_review-rank&ds=v1%3A4EnYKXVQA7DIE41qCvRZoNB4qN92Jlztd3BPsTFXmxU',+ 'https://reddit.com',+ 'https://codepen.io/geheimschriftstift/pen/mPLvQz',+ 'https://www.google.com/search?q=google+hi&oq=google+hi&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQRRhA0gEIMjI2NmowajSoAgCwAgE&sourceid=chrome&ie=UTF-8',+ 'https://amazon.com',+ 'https://github.com',+ ]++ await browser_session.start()+ page = await browser_session.get_current_page()++ for website in websites:+ # sleep 2+ await page.goto(website)+ await asyncio.sleep(1)++ last_clicked_index = None # Track the index for text input+ while True:+ try:+ await remove_highlighting_script(browser_session)++ page = await browser_session.get_current_page()+ async with DomService(browser_session, page) as dom_service:+ all_elements_state = await dom_service.get_serialized_dom_tree()++ print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')++ # Get/refresh the state (includes removing old highlights)+ print('\nGetting page state...')++ start_time = time.time()+ all_elements_state = await browser_session.get_state_summary(True)+ end_time = time.time()+ print(f'get_state_summary took {end_time - start_time:.2f} seconds')++ selector_map = all_elements_state.dom_state.selector_map+ total_elements = len(selector_map.keys())+ print(f'Total number of elements: {total_elements}')++ # print(all_elements_state.element_tree.clickable_elements_to_string())+ prompt = AgentMessagePrompt(+ browser_state_summary=all_elements_state,+ file_system=FileSystem(base_dir='./tmp'),+ include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,+ step_info=None,+ )+ # Write the user message to a file for analysis+ user_message = prompt.get_user_message(use_vision=False).text++ # clickable_elements_str = all_elements_state.element_tree.clickable_elements_to_string()++ text_to_save = user_message++ os.makedirs('./tmp', exist_ok=True)+ async with await anyio.open_file('./tmp/user_message.txt', 'w', encoding='utf-8') as f:+ await f.write(text_to_save)++ # save pure clickable elements to a file+ if all_elements_state.dom_state._root:+ async with await anyio.open_file('./tmp/element_tree.json', 'w', encoding='utf-8') as f:+ await f.write(json.dumps(all_elements_state.dom_state._root.original_node.__json__(), indent=0))++ # copy the user message to the clipboard+ # pyperclip.copy(text_to_save)++ encoding = tiktoken.encoding_for_model('gpt-4o')+ token_count = len(encoding.encode(text_to_save))+ print(f'Token count: {token_count}')++ print('User message written to ./tmp/user_message.txt')+ print('Element tree written to ./tmp/element_tree.json')++ # also save all_elements_state.element_tree.clickable_elements_to_string() to a file+ # with open('./tmp/clickable_elements.json', 'w', encoding='utf-8') as f:+ # f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=2))+ # print('Clickable elements written to ./tmp/clickable_elements.json')++ await inject_highlighting_script(browser_session, selector_map)++ answer = input(+ "Enter element index to click, 'index,text' to input, 'c,index' to copy element JSON, or 'q' to quit: "+ )++ if answer.lower() == 'q':+ break++ try:+ if answer.lower().startswith('c,'):+ # Copy element JSON format: c,index+ parts = answer.split(',', 1)+ if len(parts) == 2:+ try:+ target_index = int(parts[1].strip())+ if target_index in selector_map:+ element_node = selector_map[target_index]+ element_json = json.dumps(element_node.__json__(), indent=2, default=str)+ pyperclip.copy(element_json)+ print(f'Copied element {target_index} JSON to clipboard: {element_node.tag_name}')+ else:+ print(f'Invalid index: {target_index}')+ except ValueError:+ print(f'Invalid index format: {parts[1]}')+ else:+ print("Invalid input format. Use 'c,index'.")+ elif ',' in answer:+ # Input text format: index,text+ parts = answer.split(',', 1)+ if len(parts) == 2:+ try:+ target_index = int(parts[0].strip())+ text_to_input = parts[1]+ if target_index in selector_map:+ element_node = selector_map[target_index]+ print(+ f"Inputting text '{text_to_input}' into element {target_index}: {element_node.tag_name}"+ )+ await browser_session._input_text_element_node(element_node, text_to_input)+ print('Input successful.')+ else:+ print(f'Invalid index: {target_index}')+ except ValueError:+ print(f'Invalid index format: {parts[0]}')+ else:+ print("Invalid input format. Use 'index,text'.")+ else:+ # Click element format: index+ try:+ clicked_index = int(answer)+ if clicked_index in selector_map:+ element_node = selector_map[clicked_index]+ print(f'Clicking element {clicked_index}: {element_node.tag_name}')+ await browser_session._click_element_node(element_node)+ print('Click successful.')+ else:+ print(f'Invalid index: {clicked_index}')+ except ValueError:+ print(f"Invalid input: '{answer}'. Enter an index, 'index,text', 'c,index', or 'q'.")++ except Exception as action_e:+ print(f'Action failed: {action_e}')++ # No explicit highlight removal here, get_state handles it at the start of the loop++ except Exception as e:+ print(f'Error in loop: {e}')+ # Optionally add a small delay before retrying+ await asyncio.sleep(1)+++if __name__ == '__main__':+ asyncio.run(test_focus_vs_all_elements())+ # asyncio.run(test_process_html_file()) # Commented out the other testdiff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 32519b5b4..92c04b0f7 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -42,7 +42,7 @@ class DomService:self.page = pageself.cdp_client: CDPClient | None = None- self.playwright_page_to_session_id_store: dict[str, str] = {}+ # self.playwright_page_to_session_id_store: dict[str, str] = {}async def _get_cdp_client(self) -> CDPClient:if not self.browser.cdp_url:@@ -82,7 +82,8 @@ class DomService:TODO: this is a REALLY hacky way -> if multiple same urls are open then this will break"""- page_guid = self.page._impl_obj._guid+ # page_guid = self.page._impl_obj._guid+ # TODO: add cache for page to sessionId# if page_guid in self.page_to_session_id_store:# return self.page_to_session_id_store[page_guid]@@ -93,7 +94,7 @@ class DomService:for target in targets['targetInfos']:if target['type'] == 'page' and target['url'] == self.page.url:# cache the session id for this playwright page- self.playwright_page_to_session_id_store[page_guid] = target['targetId']+ # self.playwright_page_to_session_id_store[page_guid] = target['targetId']session = await cdp_client.send.Target.attachToTarget(params={'targetId': target['targetId'], 'flatten': True})session_id = session['sessionId']