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
create relative paths from shadow elements
Gregor Žuničb48bc0f686c9
diff --git a/browser_use/dom/process_dom.js b/browser_use/dom/process_dom.jsindex 4115c7701..9ec03f211 100644--- a/browser_use/dom/process_dom.js+++ b/browser_use/dom/process_dom.js@@ -1,21 +1,34 @@() => {// Helper function to generate XPath as a tree- function getXPathTree(element) {+ function getXPathTree(element, stopAtBoundary = true) {const segments = [];- while (element && element.nodeType === Node.ELEMENT_NODE) {+ let currentElement = element;++ while (currentElement && currentElement.nodeType === Node.ELEMENT_NODE) {+ // Stop if we hit a shadow root or iframe+ if (stopAtBoundary &&+ (currentElement.parentNode instanceof ShadowRoot ||+ currentElement.parentNode instanceof HTMLIFrameElement)) {+ break;+ }+let index = 0;- let sibling = element.previousSibling;+ let sibling = currentElement.previousSibling;while (sibling) {- if (sibling.nodeType === Node.ELEMENT_NODE && sibling.nodeName === element.nodeName) {+ if (sibling.nodeType === Node.ELEMENT_NODE &&+ sibling.nodeName === currentElement.nodeName) {index++;}sibling = sibling.previousSibling;}- const tagName = element.nodeName.toLowerCase();++ const tagName = currentElement.nodeName.toLowerCase();const xpathIndex = index > 0 ? `[${index + 1}]` : '';segments.unshift(`${tagName}${xpathIndex}`);- element = element.parentNode;++ currentElement = currentElement.parentNode;}+return segments.join('/');}@@ -38,7 +51,7 @@const nodeData = {tagName: node.tagName ? node.tagName.toLowerCase() : null,attributes: {},- xpath: node.nodeType === Node.ELEMENT_NODE ? getXPathTree(node) : null,+ xpath: node.nodeType === Node.ELEMENT_NODE ? getXPathTree(node, true) : null,children: []};diff --git a/browser_use/dom/tests/process_dom_test.py b/browser_use/dom/tests/process_dom_test.pyindex 797b4bd1d..36badb54d 100644--- a/browser_use/dom/tests/process_dom_test.py+++ b/browser_use/dom/tests/process_dom_test.py@@ -16,7 +16,7 @@ async def test_process_dom():# browser.go_to_url('https://google.com/flights')await page.goto('https://immobilienscout24.de')- time.sleep(3)+ time.sleep(1.5)with open('browser_use/dom/process_dom.js', 'r') as f:js_code = f.read()@@ -30,6 +30,6 @@ async def test_process_dom():os.makedirs('./tmp', exist_ok=True)with open('./tmp/dom.json', 'w') as f:- json.dump(dom_tree, f, indent=2)+ json.dump(dom_tree, f, indent=1)input('Press Enter to continue...')