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
Debug page structure
Magnus Müllerda4128ed3a3b
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 9deaf549d..7f793b5ac 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -669,6 +669,57 @@ class BrowserContext:page = await self.get_current_page()return await page.evaluate(script)+ async def get_page_structure(self) -> str:+ """Get a debug view of the page structure including iframes"""+ debug_script = """(() => {+ function getPageStructure(element = document, depth = 0, maxDepth = 10) {+ if (depth >= maxDepth) return '';++ const indent = ' '.repeat(depth);+ let structure = '';++ // Add current element info if it's not the document+ if (element !== document) {+ const tagName = element.tagName.toLowerCase();+ const id = element.id ? `#${element.id}` : '';+ const classes = element.className && typeof element.className === 'string' ?+ `.${element.className.split(' ').join('.')}` : '';+ structure += `${indent}${tagName}${id}${classes}\\n`;++ // Handle iframes specially+ if (tagName === 'iframe') {+ try {+ const iframeDoc = element.contentDocument || element.contentWindow?.document;+ if (iframeDoc) {+ structure += `${indent} [IFRAME CONTENT]:\\n`;+ structure += getPageStructure(iframeDoc, depth + 2, maxDepth);+ } else {+ structure += `${indent} [IFRAME: No access to content]\\n`;+ }+ } catch (e) {+ structure += `${indent} [IFRAME: ${e.message}]\\n`;+ }+ }+ }++ // Get all child elements+ const children = element.children || element.childNodes;+ for (const child of children) {+ if (child.nodeType === 1) { // Element nodes only+ structure += getPageStructure(child, depth + 1, maxDepth);+ }+ }++ return structure;+ }++ return getPageStructure();+ })()"""++ page = await self.get_current_page()+ structure = await page.evaluate(debug_script)+ return structure+@time_execution_sync('--get_state') # This decorator might need to be updated to handle asyncasync def get_state(self) -> BrowserState:"""Get the current state of the browser"""diff --git a/browser_use/dom/tests/debug_page_structure.py b/browser_use/dom/tests/debug_page_structure.pynew file mode 100644index 000000000..f55df33c7--- /dev/null+++ b/browser_use/dom/tests/debug_page_structure.py@@ -0,0 +1,41 @@+import asyncio+import os+import sys++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from browser_use.browser.browser import Browser, BrowserConfig+from browser_use.browser.context import BrowserContext+++async def analyze_page_structure(url: str):+ """Analyze and print the structure of a webpage"""+ browser = Browser(+ config=BrowserConfig(+ headless=False, # Set to True if you don't need to see the browser+ )+ )++ context = BrowserContext(browser=browser)++ try:+ async with context as ctx:+ # Navigate to the URL+ page = await ctx.get_current_page()+ await page.goto(url)+ await page.wait_for_load_state('networkidle')++ # Get and print the page structure+ structure = await ctx.get_page_structure()+ print(f'\nPage Structure for {url}:\n')+ print(structure)++ input('Press Enter to close the browser...')+ finally:+ await browser.close()+++if __name__ == '__main__':+ # You can modify this URL to analyze different pages+ url = 'https://reddit.com'+ asyncio.run(analyze_page_structure(url))