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
added highliting for ifreames
Gregor Žuničcb4688409e64
diff --git a/browser_use/dom/process_dom.js b/browser_use/dom/process_dom.jsindex 58178a491..807c125c5 100644--- a/browser_use/dom/process_dom.js+++ b/browser_use/dom/process_dom.js@@ -1,4 +1,30 @@+let highlightIndex = 0;++function highlightElement(element, index) {+ element.style.outline = "2px solid red";+ element.setAttribute('browser-user-highlight-id', 'playwright-highlight');++ const label = document.createElement("div");+ label.className = 'playwright-highlight-label';+ label.style.position = "fixed";+ label.style.background = "red";+ label.style.color = "white";+ label.style.padding = "2px 6px";+ label.style.borderRadius = "10px";+ label.style.fontSize = "12px";+ label.style.zIndex = "9999999";+ label.textContent = index;++ const rect = element.getBoundingClientRect();+ label.style.top = (rect.top - 20) + "px";+ label.style.left = rect.left + "px";+ document.body.appendChild(label);++ return index + 1;+}+() => {+// Helper function to generate XPath as a treefunction getXPathTree(element, stopAtBoundary = true) {const segments = [];@@ -30,6 +56,183 @@return segments.join('/');}+ // Helper function to check if element is accepted+ function isElementAccepted(element) {+ const leafElementDenyList = new Set(['svg', 'script', 'style', 'link', 'meta']);+ return !leafElementDenyList.has(element.tagName.toLowerCase());+ }++ // Helper function to check if element is interactive+ function isInteractiveElement(element) {+ // Base interactive elements and roles+ const interactiveElements = new Set([+ 'a', 'button', 'details', 'embed', 'input', 'label',+ 'menu', 'menuitem', 'object', 'select', 'textarea', 'summary'+ ]);++ const interactiveRoles = new Set([+ 'button', 'menu', 'menuitem', 'link', 'checkbox', 'radio',+ 'slider', 'tab', 'tabpanel', 'textbox', 'combobox', 'grid',+ 'listbox', 'option', 'progressbar', 'scrollbar', 'searchbox',+ 'switch', 'tree', 'treeitem', 'spinbutton', 'tooltip',+ 'menuitemcheckbox', 'menuitemradio'+ ]);++ const tagName = element.tagName.toLowerCase();+ const role = element.getAttribute('role');+ const ariaRole = element.getAttribute('aria-role');+ const tabIndex = element.getAttribute('tabindex');++ // Basic role/attribute checks+ const hasInteractiveRole = interactiveElements.has(tagName) ||+ interactiveRoles.has(role) ||+ interactiveRoles.has(ariaRole) ||+ tabIndex === '0';++ if (hasInteractiveRole) return true;++ // Get computed style+ const style = window.getComputedStyle(element);++ // Check if element has click-like styling+ // const hasClickStyling = style.cursor === 'pointer' ||+ // element.style.cursor === 'pointer' ||+ // style.pointerEvents !== 'none';++ // Check for event listeners+ const hasClickHandler = element.onclick !== null ||+ element.getAttribute('onclick') !== null ||+ element.hasAttribute('ng-click') ||+ element.hasAttribute('@click') ||+ element.hasAttribute('v-on:click');++ // Helper function to safely get event listeners+ function getEventListeners(el) {+ try {+ // Try to get listeners using Chrome DevTools API+ return window.getEventListeners?.(el) || {};+ } catch (e) {+ // Fallback: check for common event properties+ const listeners = {};++ // List of common event types to check+ const eventTypes = [+ 'click', 'mousedown', 'mouseup',+ 'touchstart', 'touchend', 'keydown',+ 'keyup', 'focus', 'blur'+ ];++ for (const type of eventTypes) {+ const handler = el[`on${type}`];+ if (handler) {+ listeners[type] = [{+ listener: handler,+ useCapture: false+ }];+ }+ }++ return listeners;+ }+ }++ // Check for click-related events on the element itself+ const listeners = getEventListeners(element);+ const hasClickListeners = listeners && (+ listeners.click?.length > 0 ||+ listeners.mousedown?.length > 0 ||+ listeners.mouseup?.length > 0 ||+ listeners.touchstart?.length > 0 ||+ listeners.touchend?.length > 0+ );++ // Check for ARIA properties that suggest interactivity+ const hasAriaProps = element.hasAttribute('aria-expanded') ||+ element.hasAttribute('aria-pressed') ||+ element.hasAttribute('aria-selected') ||+ element.hasAttribute('aria-checked');++ // Check for form-related functionality+ const isFormRelated = element.form !== undefined ||+ element.hasAttribute('contenteditable') ||+ style.userSelect !== 'none';++ // Check if element is draggable+ const isDraggable = element.draggable ||+ element.getAttribute('draggable') === 'true';++ return hasAriaProps ||+ // hasClickStyling ||+ hasClickHandler ||+ hasClickListeners ||+ // isFormRelated ||+ isDraggable;++ }++ // Helper function to check if element is visible+ function isElementVisible(element) {+ const style = window.getComputedStyle(element);+ return element.offsetWidth > 0 &&+ element.offsetHeight > 0 &&+ style.visibility !== 'hidden' &&+ style.display !== 'none';+ }++ // Helper function to check if element is the top element at its position+ function isTopElement(element) {+ // Find the correct document context and root element+ let doc = element.ownerDocument;+ let rootContext = doc.documentElement;++ // If we're in an iframe or shadow DOM, adjust accordingly+ if (doc !== window.document) {+ return true; // Elements in iframes are considered top by default+ } else if (element.getRootNode() instanceof ShadowRoot) {+ rootContext = element.getRootNode().host;+ }++ const rect = element.getBoundingClientRect();+ const points = [+ { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }+ ];++ return points.some(point => {+ let topEl;+ try {+ topEl = doc.elementFromPoint(point.x, point.y);+ if (!topEl) return false;++ // Check if the element or any of its parents match our target element+ let current = topEl;+ while (current && current !== rootContext) {+ if (current === element) return true;+ current = current.parentElement;+ }+ } catch (e) {+ // If we can't determine the top element, consider it visible+ return true;+ }+ return false;+ });+ }++ // Helper function to check if text node is visible+ function isTextNodeVisible(textNode) {+ const range = document.createRange();+ range.selectNodeContents(textNode);+ const rect = range.getBoundingClientRect();++ return rect.width !== 0 &&+ rect.height !== 0 &&+ rect.top >= 0 &&+ rect.top <= window.innerHeight &&+ textNode.parentElement.checkVisibility({+ checkOpacity: true,+ checkVisibilityCSS: true+ });+ }+// Function to traverse the DOM and create nested JSONfunction buildDomTree(node, parentIframe = null) {if (!node) return null;@@ -37,22 +240,47 @@// Special case for text nodesif (node.nodeType === Node.TEXT_NODE) {const textContent = node.textContent.trim();- if (textContent) {+ if (textContent && isTextNodeVisible(node)) {+ // Highlight text node's parent element since we can't highlight text nodes directly+ // highlightIndex = highlightElement(node.parentElement, highlightIndex);return {type: "TEXT_NODE",- text: textContent+ text: textContent,+ isVisible: true,+ // highlightIndex: highlightIndex - 1};}return null;}+ // Check if element is accepted+ if (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {+ return null;+ }+const nodeData = {tagName: node.tagName ? node.tagName.toLowerCase() : null,attributes: {},xpath: node.nodeType === Node.ELEMENT_NODE ? getXPathTree(node, true) : null,- children: []+ children: [],};+ if (node.nodeType === Node.ELEMENT_NODE) {+ const isInteractive = isInteractiveElement(node);+ const isVisible = isElementVisible(node);+ const isTop = isTopElement(node);++ nodeData.isInteractive = isInteractive;+ nodeData.isVisible = isVisible;+ nodeData.isTopElement = isTop;++ // Highlight if element meets all criteria+ if (isInteractive && isVisible && isTop) {+ highlightIndex = highlightElement(node, highlightIndex);+ nodeData.highlightIndex = highlightIndex - 1;+ }+ }+// Copy all attributes if the node is an elementif (node.nodeType === Node.ELEMENT_NODE && node.attributes) {for (const attr of node.attributes) {diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 37349e57d..d17b6e69a 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -128,7 +128,7 @@ class DomService:if result.isVisible and result.isTopElement:text_content = self._extract_text_from_all_children(element)tag_name = element.name- attributes = self._get_essential_attributes(element)+ attributes = self._get_all_attributes(element)output_string = f"<{tag_name}{' ' + attributes if attributes else ''}>{text_content}</{tag_name}>"depth = len(xpath.split('/')) - 2@@ -139,7 +139,7 @@ class DomService:if xpath in text_results.texts:result = text_results.texts[xpath]if result.isVisible:- text_content = self._cap_text_length(text_node.strip())+ text_content = text_node.strip()if text_content:depth = len(xpath.split('/')) - 2ordered_results.append((order, xpath, False, text_content, depth, True))@@ -290,11 +290,6 @@ class DomService:logger.error('Error in batch text check: %s', e)return BatchCheckResults(elements={}, texts={})- def _cap_text_length(self, text: str, max_length: int = 250) -> str:- if len(text) > max_length:- half_length = max_length // 2- return text[:half_length] + '...' + text[-half_length:]- return textdef _extract_text_from_all_children(self, element: Tag) -> str:# Tell BeautifulSoup that button tags can contain content@@ -310,7 +305,7 @@ class DomService:text_content += '\n' + current_child_text- return self._cap_text_length(text_content.strip()) or ''+ return text_content.strip() or ''def _is_interactive_element(self, element: Tag) -> bool:"""Check if element is interactive based on tag name and attributes."""@@ -384,7 +379,7 @@ class DomService:def _is_element_accepted(self, element: Tag) -> bool:"""Check if element is accepted based on tag name and special cases."""- leaf_element_deny_list = {'svg', 'iframe', 'script', 'style', 'link', 'meta'}+ leaf_element_deny_list = {'svg', 'script', 'style', 'link', 'meta'}# First check if it's in deny listif element.name in leaf_element_deny_list:@@ -392,72 +387,3 @@ class DomService:return element.name not in leaf_element_deny_list- 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',- 'readonly',- 'disabled',- 'checked',- 'selected',- 'role',- 'type', # Important for inputs, buttons- 'name', # Important for form elements- 'value', # Current value of form elements- 'placeholder', # Helpful for understanding input purpose- 'title', # Additional descriptive text- 'alt', # Alternative text for images- 'for', # Important for label associations- 'autocomplete', # Form field behavior- ]-- # These attributes should never be capped- no_cap_attributes = {- 'href', # URLs should never be capped- 'src', # Source URLs should never be capped- 'action', # Form submission URLs should never be capped- }-- # Collect essential attributes that have values- attrs = []- for attr in essential_attributes:- if attr in element.attrs:- element_attr = element[attr]- if isinstance(element_attr, str):- element_attr = element_attr- elif isinstance(element_attr, (list, tuple)):- element_attr = ' '.join(str(v) for v in element_attr)-- if attr not in no_cap_attributes:- element_attr = self._cap_text_length(element_attr, 25)-- attrs.append(f'{attr}="{element_attr}"')-- state_attributes_prefixes = (- 'aria-',- 'data-',- )-- # Collect data- attributes- for attr in element.attrs:- if attr.startswith(state_attributes_prefixes):- attrs.append(f'{attr}="{element[attr]}"')-- return ' '.join(attrs)-- 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/browser_use/dom/tests/process_dom_test.py b/browser_use/dom/tests/process_dom_test.pyindex f7d19dcd1..d36d6bfdb 100644--- a/browser_use/dom/tests/process_dom_test.py+++ b/browser_use/dom/tests/process_dom_test.py@@ -14,10 +14,10 @@ async def test_process_dom():# await page.goto('https://kayak.com/flights')# browser.go_to_url('https://google.com/flights')- # await page.goto('https://immobilienscout24.de')- await page.goto('https://www.w3schools.com/html/html_iframe.asp')+ await page.goto('https://immobilienscout24.de')+ # await page.goto('https://seleniumbase.io/w3schools/iframes')- time.sleep(1.5)+ time.sleep(3)with open('browser_use/dom/process_dom.js', 'r') as f:js_code = f.read()