Skip to content

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

first js dom processor, to get all elements

Gregor Žunič6691cc05dcd5
diff --git a/browser_use/dom/process_dom.js b/browser_use/dom/process_dom.js
new file mode 100644
index 000000000..4115c7701
--- /dev/null
+++ b/browser_use/dom/process_dom.js
@@ -0,0 +1,89 @@
+() => {
+ // Helper function to generate XPath as a tree
+ function getXPathTree(element) {
+ const segments = [];
+ while (element && element.nodeType === Node.ELEMENT_NODE) {
+ let index = 0;
+ let sibling = element.previousSibling;
+ while (sibling) {
+ if (sibling.nodeType === Node.ELEMENT_NODE && sibling.nodeName === element.nodeName) {
+ index++;
+ }
+ sibling = sibling.previousSibling;
+ }
+ const tagName = element.nodeName.toLowerCase();
+ const xpathIndex = index > 0 ? `[${index + 1}]` : '';
+ segments.unshift(`${tagName}${xpathIndex}`);
+ element = element.parentNode;
+ }
+ return segments.join('/');
+ }
+
+ // Function to traverse the DOM and create nested JSON
+ function buildDomTree(node, parentIframe = null) {
+ if (!node) return null;
+
+ // Special case for text nodes
+ if (node.nodeType === Node.TEXT_NODE) {
+ const textContent = node.textContent.trim();
+ if (textContent) {
+ return {
+ type: "TEXT_NODE",
+ text: textContent
+ };
+ }
+ return null;
+ }
+
+ const nodeData = {
+ tagName: node.tagName ? node.tagName.toLowerCase() : null,
+ attributes: {},
+ xpath: node.nodeType === Node.ELEMENT_NODE ? getXPathTree(node) : null,
+ children: []
+ };
+
+ // Only add iframeContext if we're inside an iframe
+ if (parentIframe) {
+ nodeData.iframeContext = `iframe[src="${parentIframe.src || ''}"]`;
+ }
+
+ // Only add shadowRoot field if it exists
+ if (node.shadowRoot) {
+ nodeData.shadowRoot = true;
+ }
+
+ // Handle shadow DOM
+ if (node.shadowRoot) {
+ const shadowChildren = Array.from(node.shadowRoot.childNodes).map(child =>
+ buildDomTree(child, parentIframe)
+ );
+ nodeData.children.push(...shadowChildren);
+ }
+
+ // Handle iframes
+ if (node.tagName === 'IFRAME') {
+ try {
+ const iframeDoc = node.contentDocument || node.contentWindow.document;
+ if (iframeDoc) {
+ const iframeChildren = Array.from(iframeDoc.body.childNodes).map(child =>
+ buildDomTree(child, node)
+ );
+ nodeData.children.push(...iframeChildren);
+ }
+ } catch (e) {
+ console.warn('Unable to access iframe:', node);
+ }
+ } else {
+ // Traverse child nodes
+ const children = Array.from(node.childNodes).map(child =>
+ buildDomTree(child, parentIframe)
+ );
+ nodeData.children.push(...children);
+ }
+
+ return nodeData;
+ }
+
+ // Start from the document body
+ return buildDomTree(document.body);
+}
\ No newline at end of file
diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.py
index 33c97120c..7b145cae5 100644
--- a/browser_use/dom/tests/extraction_test.py
+++ b/browser_use/dom/tests/extraction_test.py
@@ -9,15 +9,15 @@ from browser_use.utils import time_execution_sync
# @pytest.mark.skip("slow af")
async def test_process_html_file():
- browser = Browser(headless=False)
+ browser = Browser(headless=True)
page = await browser.get_current_page()
dom_service = DomService(page)
- await page.goto('https://kayak.com/flights')
+ # await page.goto('https://kayak.com/flights')
# browser.go_to_url('https://google.com/flights')
- # browser.go_to_url('https://immobilienscout24.de')
+ await page.goto('https://immobilienscout24.de')
time.sleep(3)
# browser._click_element_by_xpath(
diff --git a/browser_use/dom/tests/process_dom_test.py b/browser_use/dom/tests/process_dom_test.py
new file mode 100644
index 000000000..797b4bd1d
--- /dev/null
+++ b/browser_use/dom/tests/process_dom_test.py
@@ -0,0 +1,35 @@
+import json
+import os
+import time
+
+from browser_use.browser.service import Browser
+
+
+async def test_process_dom():
+ browser = Browser(headless=False)
+
+ page = await browser.get_current_page()
+
+ # dom_service = DomService(page)
+
+ # await page.goto('https://kayak.com/flights')
+ # browser.go_to_url('https://google.com/flights')
+ await page.goto('https://immobilienscout24.de')
+
+ time.sleep(3)
+
+ with open('browser_use/dom/process_dom.js', 'r') as f:
+ js_code = f.read()
+
+ start = time.time()
+ dom_tree = await page.evaluate(js_code)
+ end = time.time()
+
+ # print(dom_tree)
+ print(f'Time: {end - start:.2f}s')
+
+ os.makedirs('./tmp', exist_ok=True)
+ with open('./tmp/dom.json', 'w') as f:
+ json.dump(dom_tree, f, indent=2)
+
+ input('Press Enter to continue...')