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
Unify extract in actor and tools
Magnus Müller20f8ef81e194
diff --git a/browser_use/actor/page.py b/browser_use/actor/page.pyindex bed479e45..b45fd7a4b 100644--- a/browser_use/actor/page.py+++ b/browser_use/actor/page.py@@ -470,47 +470,11 @@ Before you return the element index, reason about the state and elements for a sif not llm:raise ValueError('LLM not provided')- # Extract clean markdown from the page- session_id = await self._ensure_session()+ # Extract clean markdown using the same method as in tools/service.pytry:- body_id = await self._client.send.DOM.getDocument(session_id=session_id)- page_html_result = await self._client.send.DOM.getOuterHTML(- params={'backendNodeId': body_id['root']['backendNodeId']}, session_id=session_id- )- page_html = page_html_result['outerHTML']+ content, content_stats = await self._extract_clean_markdown()except Exception as e:- raise RuntimeError(f"Couldn't extract page content: {e}")-- # Convert HTML to clean markdown- import html2text-- h = html2text.HTML2Text()- h.ignore_links = False- h.ignore_images = True- h.ignore_emphasis = False- h.body_width = 0 # Don't wrap lines- h.unicode_snob = True- h.skip_internal_links = True- markdown_content = h.handle(page_html)-- # Clean up the markdown- import re-- # Remove URL encoding artifacts- markdown_content = re.sub(r'%[0-9A-Fa-f]{2}', '', markdown_content)-- # Compress excessive newlines- markdown_content = re.sub(r'\n{4,}', '\n\n\n', markdown_content)-- # Remove very short lines (likely artifacts)- lines = markdown_content.split('\n')- filtered_lines = []- for line in lines:- stripped = line.strip()- if len(stripped) > 2: # Keep lines with substantial content- filtered_lines.append(line)-- markdown_content = '\n'.join(filtered_lines).strip()+ raise RuntimeError(f'Could not extract clean markdown: {type(e).__name__}')# System prompt for structured extractionsystem_prompt = """@@ -535,7 +499,7 @@ You will be given a query and the markdown of a webpage that has been filtered t""".strip()# Build prompt with just query and content- prompt_content = f'<query>\n{prompt}\n</query>\n\n<webpage_content>\n{markdown_content}\n</webpage_content>'+ prompt_content = f'<query>\n{prompt}\n</query>\n\n<webpage_content>\n{content}\n</webpage_content>'# Send to LLM with structured outputimport asyncio@@ -552,3 +516,13 @@ You will be given a query and the markdown of a webpage that has been filtered treturn response.completionexcept Exception as e:raise RuntimeError(str(e))++ async def _extract_clean_markdown(self, extract_links: bool = False) -> tuple[str, dict]:+ """Extract clean markdown from the current page using enhanced DOM tree.++ Uses the shared markdown extractor for consistency with tools/service.py.+ """+ from browser_use.dom.markdown_extractor import extract_clean_markdown++ dom_service = self.dom_service+ return await extract_clean_markdown(dom_service=dom_service, target_id=self._target_id, extract_links=extract_links)diff --git a/browser_use/dom/markdown_extractor.py b/browser_use/dom/markdown_extractor.pynew file mode 100644index 000000000..9baf673bb--- /dev/null+++ b/browser_use/dom/markdown_extractor.py@@ -0,0 +1,169 @@+"""+Shared markdown extraction utilities for browser content processing.++This module provides a unified interface for extracting clean markdown from browser content,+used by both the tools service and page actor.+"""++import re+from typing import TYPE_CHECKING, Any, Dict, Tuple++from browser_use.dom.serializer.html_serializer import HTMLSerializer+from browser_use.dom.service import DomService++if TYPE_CHECKING:+ from browser_use.browser.session import BrowserSession+ from browser_use.browser.watchdogs.dom_watchdog import DOMWatchdog+++async def extract_clean_markdown(+ browser_session: 'BrowserSession | None' = None,+ dom_service: DomService | None = None,+ target_id: str | None = None,+ extract_links: bool = False,+) -> Tuple[str, Dict[str, Any]]:+ """Extract clean markdown from browser content using enhanced DOM tree.++ This unified function can extract markdown using either a browser session (for tools service)+ or a DOM service with target ID (for page actor).++ Args:+ browser_session: Browser session to extract content from (tools service path)+ dom_service: DOM service instance (page actor path)+ target_id: Target ID for the page (required when using dom_service)+ extract_links: Whether to preserve links in markdown++ Returns:+ tuple: (clean_markdown_content, content_statistics)++ Raises:+ ValueError: If neither browser_session nor (dom_service + target_id) are provided+ """+ # Validate input parameters+ if browser_session is not None:+ if dom_service is not None or target_id is not None:+ raise ValueError('Cannot specify both browser_session and dom_service/target_id')+ # Browser session path (tools service)+ enhanced_dom_tree = await _get_enhanced_dom_tree_from_browser_session(browser_session)+ current_url = await browser_session.get_current_page_url()+ method = 'enhanced_dom_tree'+ elif dom_service is not None and target_id is not None:+ # DOM service path (page actor)+ enhanced_dom_tree = await dom_service.get_dom_tree(target_id=target_id)+ current_url = None # Not available via DOM service+ method = 'dom_service'+ else:+ raise ValueError('Must provide either browser_session or both dom_service and target_id')++ # Use the HTML serializer with the enhanced DOM tree+ html_serializer = HTMLSerializer(extract_links=extract_links)+ page_html = html_serializer.serialize(enhanced_dom_tree)++ original_html_length = len(page_html)++ # Use markdownify for clean markdown conversion+ from markdownify import markdownify as md++ content = md(+ page_html,+ heading_style='ATX', # Use # style headings+ strip=['script', 'style'], # Remove these tags+ bullets='-', # Use - for unordered lists+ code_language='', # Don't add language to code blocks+ escape_asterisks=False, # Don't escape asterisks (cleaner output)+ escape_underscores=False, # Don't escape underscores (cleaner output)+ escape_misc=False, # Don't escape other characters (cleaner output)+ autolinks=False, # Don't convert URLs to <> format+ default_title=False, # Don't add default title attributes+ keep_inline_images_in=[], # Don't keep inline images in any tags (we already filter base64 in HTML)+ )++ initial_markdown_length = len(content)++ # Minimal cleanup - markdownify already does most of the work+ content = re.sub(r'%[0-9A-Fa-f]{2}', '', content) # Remove any remaining URL encoding++ # Apply light preprocessing to clean up excessive whitespace+ content, chars_filtered = _preprocess_markdown_content(content)++ final_filtered_length = len(content)++ # Content statistics+ stats = {+ 'method': method,+ 'original_html_chars': original_html_length,+ 'initial_markdown_chars': initial_markdown_length,+ 'filtered_chars_removed': chars_filtered,+ 'final_filtered_chars': final_filtered_length,+ }++ # Add URL to stats if available+ if current_url:+ stats['url'] = current_url++ return content, stats+++async def _get_enhanced_dom_tree_from_browser_session(browser_session: 'BrowserSession'):+ """Get enhanced DOM tree from browser session via DOMWatchdog."""+ # Get the enhanced DOM tree from DOMWatchdog+ # This captures the current state of the page including dynamic content, shadow roots, etc.+ dom_watchdog: DOMWatchdog | None = browser_session._dom_watchdog+ assert dom_watchdog is not None, 'DOMWatchdog not available'++ # Use cached enhanced DOM tree if available, otherwise build it+ if dom_watchdog.enhanced_dom_tree is not None:+ return dom_watchdog.enhanced_dom_tree++ # Build the enhanced DOM tree if not cached+ await dom_watchdog._build_dom_tree_without_highlights()+ enhanced_dom_tree = dom_watchdog.enhanced_dom_tree+ assert enhanced_dom_tree is not None, 'Enhanced DOM tree not available'++ return enhanced_dom_tree+++# Legacy aliases removed - all code now uses the unified extract_clean_markdown function+++def _preprocess_markdown_content(content: str, max_newlines: int = 3) -> Tuple[str, int]:+ """+ Light preprocessing of markdown output - minimal cleanup with JSON blob removal.++ Args:+ content: Markdown content to lightly filter+ max_newlines: Maximum consecutive newlines to allow++ Returns:+ tuple: (filtered_content, chars_filtered)+ """+ original_length = len(content)++ # Remove JSON blobs (common in SPAs like LinkedIn, Facebook, etc.)+ # These are often embedded as `{"key":"value",...}` and can be massive+ # Match JSON objects/arrays that are at least 100 chars long+ # This catches SPA state/config data without removing small inline JSON+ content = re.sub(r'`\{["\w].*?\}`', '', content, flags=re.DOTALL) # Remove JSON in code blocks+ content = re.sub(r'\{"\$type":[^}]{100,}\}', '', content) # Remove JSON with $type fields (common pattern)+ content = re.sub(r'\{"[^"]{5,}":\{[^}]{100,}\}', '', content) # Remove nested JSON objects++ # Compress consecutive newlines (4+ newlines become max_newlines)+ content = re.sub(r'\n{4,}', '\n' * max_newlines, content)++ # Remove lines that are only whitespace or very short (likely artifacts)+ lines = content.split('\n')+ filtered_lines = []+ for line in lines:+ stripped = line.strip()+ # Keep lines with substantial content+ if len(stripped) > 2:+ # Skip lines that look like JSON (start with { or [ and are very long)+ if (stripped.startswith('{') or stripped.startswith('[')) and len(stripped) > 100:+ continue+ filtered_lines.append(line)++ content = '\n'.join(filtered_lines)+ content = content.strip()++ chars_filtered = original_length - len(content)+ return content, chars_filtereddiff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex ea8ae6847..4d08ad5f4 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -3,7 +3,7 @@ import enumimport jsonimport loggingimport os-from typing import Any, Generic, TypeVar+from typing import Generic, TypeVartry:from lmnr import Laminar # type: ignore@@ -573,9 +573,13 @@ class Tools(Generic[Context]):# ConstantsMAX_CHAR_LIMIT = 30000- # Extract clean markdown using the new method+ # Extract clean markdown using the unified methodtry:- content, content_stats = await self.extract_clean_markdown(browser_session, extract_links)+ from browser_use.dom.markdown_extractor import extract_clean_markdown++ content, content_stats = await extract_clean_markdown(+ browser_session=browser_session, extract_links=extract_links+ )except Exception as e:raise RuntimeError(f'Could not extract clean markdown: {type(e).__name__}')@@ -1032,130 +1036,6 @@ You will be given a query and the markdown of a webpage that has been filtered treturn ActionResult(error=error_msg)# Custom done action for structured output- @observe_debug(ignore_input=True, ignore_output=True, name='extract_clean_markdown')- async def extract_clean_markdown(- self, browser_session: BrowserSession, extract_links: bool = False- ) -> tuple[str, dict[str, Any]]:- """Extract clean markdown from the current page.-- Args:- browser_session: Browser session to extract content from- extract_links: Whether to preserve links in markdown-- Returns:- tuple: (clean_markdown_content, content_statistics)- """- import re-- current_url = await browser_session.get_current_page_url()-- # Get the enhanced DOM tree from DOMWatchdog- # This captures the current state of the page including dynamic content, shadow roots, etc.- dom_watchdog = browser_session._dom_watchdog- assert dom_watchdog is not None, 'DOMWatchdog not available'-- # Get or build the enhanced DOM tree- await dom_watchdog._build_dom_tree_without_highlights()- enhanced_dom_tree = dom_watchdog.enhanced_dom_tree- assert enhanced_dom_tree is not None, 'Enhanced DOM tree not available'-- # Use the new HTML serializer with the enhanced DOM tree- # This serializer captures shadow roots and iframe content that getOuterHTML misses- from browser_use.dom.serializer.html_serializer import HTMLSerializer-- html_serializer = HTMLSerializer(extract_links=extract_links)- page_html = html_serializer.serialize(enhanced_dom_tree)-- original_html_length = len(page_html)- # save html to file- # with open('zzzpage_html.html', 'w') as f:- # f.write(page_html)-- # Use markdownify for clean markdown conversion- from markdownify import markdownify as md-- content = md(- page_html,- heading_style='ATX', # Use # style headings- strip=['script', 'style'], # Remove these tags- bullets='-', # Use - for unordered lists- code_language='', # Don't add language to code blocks- escape_asterisks=False, # Don't escape asterisks (cleaner output)- escape_underscores=False, # Don't escape underscores (cleaner output)- escape_misc=False, # Don't escape other characters (cleaner output)- autolinks=False, # Don't convert URLs to <> format- default_title=False, # Don't add default title attributes- keep_inline_images_in=[], # Don't keep inline images in any tags (we already filter base64 in HTML)- )-- initial_markdown_length = len(content)-- # Minimal cleanup - html2text already does most of the work- content = re.sub(r'%[0-9A-Fa-f]{2}', '', content) # Remove any remaining URL encoding-- # Apply light preprocessing to clean up excessive whitespace- content, chars_filtered = self._preprocess_markdown_content(content)-- final_filtered_length = len(content)- # save content to file- # with open('zzzcontent.md', 'w') as f:- # f.write(content)-- # Content statistics- stats = {- 'url': current_url,- 'method': 'enhanced_dom_tree', # Mark this as using the enhanced DOM tree method- 'original_html_chars': original_html_length,- 'initial_markdown_chars': initial_markdown_length,- 'filtered_chars_removed': chars_filtered,- 'final_filtered_chars': final_filtered_length,- }-- return content, stats-- def _preprocess_markdown_content(self, content: str, max_newlines: int = 3) -> tuple[str, int]:- """- Light preprocessing of markdown output - minimal cleanup with JSON blob removal.-- Args:- content: Markdown content to lightly filter- max_newlines: Maximum consecutive newlines to allow-- Returns:- tuple: (filtered_content, chars_filtered)- """- import re-- original_length = len(content)-- # Remove JSON blobs (common in SPAs like LinkedIn, Facebook, etc.)- # These are often embedded as `{"key":"value",...}` and can be massive- # Match JSON objects/arrays that are at least 100 chars long- # This catches SPA state/config data without removing small inline JSON- content = re.sub(r'`\{["\w].*?\}`', '', content, flags=re.DOTALL) # Remove JSON in code blocks- content = re.sub(r'\{"\$type":[^}]{100,}\}', '', content) # Remove JSON with $type fields (common pattern)- content = re.sub(r'\{"[^"]{5,}":\{[^}]{100,}\}', '', content) # Remove nested JSON objects-- # Compress consecutive newlines (4+ newlines become max_newlines)- content = re.sub(r'\n{4,}', '\n' * max_newlines, content)-- # Remove lines that are only whitespace or very short (likely artifacts)- lines = content.split('\n')- filtered_lines = []- for line in lines:- stripped = line.strip()- # Keep lines with substantial content- if len(stripped) > 2:- # Skip lines that look like JSON (start with { or [ and are very long)- if (stripped.startswith('{') or stripped.startswith('[')) and len(stripped) > 100:- continue- filtered_lines.append(line)-- content = '\n'.join(filtered_lines)- content = content.strip()-- chars_filtered = original_length - len(content)- return content, chars_filtereddef _register_done_action(self, output_model: type[T] | None, display_files_in_done_text: bool = True):if output_model is not None: