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
fix image URLs stripped from extracted markdown
Saurav Panda9445a9ff9e3c
diff --git a/browser_use/dom/markdown_extractor.py b/browser_use/dom/markdown_extractor.pyindex bb1fe784d..aff9736d4 100644--- a/browser_use/dom/markdown_extractor.py+++ b/browser_use/dom/markdown_extractor.py@@ -24,6 +24,7 @@ async def extract_clean_markdown(dom_service: DomService | None = None,target_id: str | None = None,extract_links: bool = False,+ extract_images: bool = False,) -> tuple[str, dict[str, Any]]:"""Extract clean markdown from browser content using enhanced DOM tree.@@ -35,6 +36,7 @@ async def extract_clean_markdown(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+ extract_images: Whether to preserve inline image src URLs in markdownReturns:tuple: (clean_markdown_content, content_statistics)@@ -68,6 +70,9 @@ async def extract_clean_markdown(# Use markdownify for clean markdown conversionfrom markdownify import markdownify as md+ # 'td', 'th', and headings are the only elements where markdownify sets the _inline context,+ # which causes img elements to be stripped to just alt text when keep_inline_images_in=[]+ _keep_inline_images_in = ['td', 'th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'] if extract_images else []content = md(page_html,heading_style='ATX', # Use # style headings@@ -79,7 +84,7 @@ async def extract_clean_markdown(escape_misc=False, # Don't escape other characters (cleaner output)autolinks=False, # Don't convert URLs to <> formatdefault_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)+ keep_inline_images_in=_keep_inline_images_in, # Include image src URLs when extract_images=True)initial_markdown_length = len(content)diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex 5e0a40b30..bdc9a17f4 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -208,9 +208,16 @@ try {if (ATTRIBUTES && ATTRIBUTES.length > 0) {item.attrs = {};for (var j = 0; j < ATTRIBUTES.length; j++) {- var val = el.getAttribute(ATTRIBUTES[j]);+ var attrName = ATTRIBUTES[j];+ var val;+ // Use resolved DOM property for src/href to get absolute URLs+ if ((attrName === 'src' || attrName === 'href') && typeof el[attrName] === 'string' && el[attrName] !== '') {+ val = el[attrName];+ } else {+ val = el.getAttribute(attrName);+ }if (val !== null) {- item.attrs[ATTRIBUTES[j]] = val.length > 500 ? val.slice(0, 500) + '...' : val;+ item.attrs[attrName] = val.length > 500 ? val.slice(0, 500) + '...' : val;}}}@@ -964,7 +971,7 @@ class Tools(Generic[Context]):)@self.registry.action(- """LLM extracts structured data from page markdown. Use when: on right page, know what to extract, haven't called before on same page+query. Can't get interactive elements. Set extract_links=True for URLs. Use start_from_char if previous extraction was truncated to extract data further down the page. When paginating across pages, pass already_collected with item identifiers (names/URLs) from prior pages to avoid duplicates.""",+ """LLM extracts structured data from page markdown. Use when: on right page, know what to extract, haven't called before on same page+query. Can't get interactive elements. Set extract_links=True for URLs. Set extract_images=True for image src URLs. Use start_from_char if previous extraction was truncated to extract data further down the page. When paginating across pages, pass already_collected with item identifiers (names/URLs) from prior pages to avoid duplicates.""",param_model=ExtractAction,)async def extract(@@ -978,12 +985,18 @@ class Tools(Generic[Context]):MAX_CHAR_LIMIT = 100000query = params['query'] if isinstance(params, dict) else params.queryextract_links = params['extract_links'] if isinstance(params, dict) else params.extract_links+ extract_images = params.get('extract_images', False) if isinstance(params, dict) else params.extract_imagesstart_from_char = params['start_from_char'] if isinstance(params, dict) else params.start_from_charoutput_schema: dict | None = params.get('output_schema') if isinstance(params, dict) else params.output_schemaalready_collected: list[str] = (params.get('already_collected', []) if isinstance(params, dict) else params.already_collected)+ # Auto-enable extract_images if query contains image-related keywords+ _IMAGE_KEYWORDS = ['image', 'photo', 'picture', 'thumbnail', 'img url', 'image url', 'photo url', 'product image']+ if not extract_images and any(kw in query.lower() for kw in _IMAGE_KEYWORDS):+ extract_images = True+# If the LLM didn't provide an output_schema, use the agent-injected extraction_schemaif output_schema is None and extraction_schema is not None:output_schema = extraction_schema@@ -1004,7 +1017,7 @@ class Tools(Generic[Context]):from browser_use.dom.markdown_extractor import extract_clean_markdowncontent, content_stats = await extract_clean_markdown(- browser_session=browser_session, extract_links=extract_links+ browser_session=browser_session, extract_links=extract_links, extract_images=extract_images)except Exception as e:raise RuntimeError(f'Could not extract clean markdown: {type(e).__name__}')diff --git a/browser_use/tools/views.py b/browser_use/tools/views.pyindex a8102ecf9..830876cc1 100644--- a/browser_use/tools/views.py+++ b/browser_use/tools/views.py@@ -10,6 +10,10 @@ class ExtractAction(BaseModel):extract_links: bool = Field(default=False, description='Set True to true if the query requires links, else false to safe tokens')+ extract_images: bool = Field(+ default=False,+ description='Set True to include image src URLs in extracted markdown. Auto-enabled when query contains image-related keywords.',+ )start_from_char: int = Field(default=0, description='Use this for long markdowns to start from a specific character (not index in browser_state)')diff --git a/tests/ci/test_extract_images.py b/tests/ci/test_extract_images.pynew file mode 100644index 000000000..562f4397f--- /dev/null+++ b/tests/ci/test_extract_images.py@@ -0,0 +1,296 @@+"""Tests for extract_images support in extract_clean_markdown.++Root cause of AGI-101: markdownify strips img src URLs when images appear inside table cells+(<td>/<th>) or heading elements, because those contexts set the _inline flag. The extract_images+parameter fixes this by adding those tags to keep_inline_images_in.++Block-level images (direct children of <div>, <figure>, etc.) are ALWAYS included in markdown+regardless of extract_images. The parameter only matters for images inside <td>, <th>, <h1>-<h6>.+"""++import asyncio++import pytest+from pytest_httpserver import HTTPServer++from browser_use.browser import BrowserProfile, BrowserSession+from browser_use.dom.markdown_extractor import extract_clean_markdown++# --- Fixtures ---++[email protected](scope='session')+def http_server():+ """Test HTTP server serving pages with product images."""+ server = HTTPServer()+ server.start()++ # Table-layout products — images are in <td>, the actual bug scenario.+ # With extract_images=False (default), img in td becomes just alt text (no URL).+ # With extract_images=True, img in td becomes  with the real URL.+ server.expect_request('/products-table').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head><title>Products Table</title></head>+ <body>+ <h1>Product Catalog</h1>+ <table>+ <thead>+ <tr><th>Image</th><th>Name</th><th>Price</th></tr>+ </thead>+ <tbody>+ <tr>+ <td><img src="http://localhost/images/widget-a.jpg" alt="Widget A"></td>+ <td>Widget A</td>+ <td>$29.99</td>+ </tr>+ <tr>+ <td><img src="http://localhost/images/widget-b.jpg" alt="Widget B"></td>+ <td>Widget B</td>+ <td>$49.99</td>+ </tr>+ <tr>+ <td><img src="http://localhost/images/gadget-c.png" alt="Gadget C"></td>+ <td>Gadget C</td>+ <td>$19.50</td>+ </tr>+ </tbody>+ </table>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ # Block-level products — images in <div>/<figure> are ALWAYS included in markdown,+ # regardless of extract_images value.+ server.expect_request('/products-block').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head><title>Products Block</title></head>+ <body>+ <div class="product">+ <img src="http://localhost/images/widget-a.jpg" alt="Widget A">+ <p>Widget A - $29.99</p>+ </div>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ server.expect_request('/text-only').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head><title>Text Only</title></head>+ <body>+ <h1>No Images Here</h1>+ <p>Just some text content with no images at all.</p>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ yield server+ server.stop()++[email protected](scope='session')+def base_url(http_server):+ return f'http://{http_server.host}:{http_server.port}'++[email protected](scope='module')+async def browser_session():+ session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=True,+ )+ )+ await session.start()+ yield session+ await session.kill()+++# --- Helper ---+++async def _navigate(browser_session, url: str):+ """Navigate to URL and wait for page load."""+ await browser_session.navigate_to(url)+ await asyncio.sleep(0.5)+++# --- Tests ---+++class TestExtractCleanMarkdown:+ """Tests for extract_clean_markdown with extract_images parameter."""++ async def test_table_images_excluded_by_default(self, browser_session, base_url):+ """Images inside <td> lose their URL with extract_images=False (default).++ This is the AGI-101 root cause: markdownify strips img src in _inline contexts+ (td/th/headings) when keep_inline_images_in=[]. The alt text is kept but not the URL.+ """+ await _navigate(browser_session, f'{base_url}/products-table')++ content, _ = await extract_clean_markdown(browser_session=browser_session, extract_images=False)++ # Alt text (product names) should still be present+ assert 'Widget A' in content+ assert 'Widget B' in content+ # But image URLs should NOT appear — img in td is stripped to alt text+ assert 'widget-a.jpg' not in content+ assert 'widget-b.jpg' not in content+ assert 'gadget-c.png' not in content+ # No markdown image syntax+ assert ' regardless+ assert '![' in content_false+ assert 'widget-a.jpg' in content_false+ assert '![' in content_true+ assert 'widget-a.jpg' in content_true++ async def test_false_is_default(self, browser_session, base_url):+ """Calling extract_clean_markdown without extract_images behaves same as extract_images=False."""+ await _navigate(browser_session, f'{base_url}/products-table')++ content_default, _ = await extract_clean_markdown(browser_session=browser_session)+ content_false, _ = await extract_clean_markdown(browser_session=browser_session, extract_images=False)++ assert content_default == content_false++ async def test_no_images_on_text_only_page(self, browser_session, base_url):+ """extract_images=True on a page with no images returns no image markdown."""+ await _navigate(browser_session, f'{base_url}/text-only')++ content, _ = await extract_clean_markdown(browser_session=browser_session, extract_images=True)++ assert '![' not in content+ assert 'No Images Here' in content or 'text content' in content+++class TestExtractImagesAutoDetection:+ """Tests for auto-detection of image-related queries in the extract action."""++ async def test_auto_detect_image_url_query(self, browser_session, base_url):+ """Query containing 'image url' auto-enables extract_images: table-cell img URLs appear in LLM input."""+ from unittest.mock import AsyncMock++ from browser_use.filesystem.file_system import FileSystem+ from browser_use.llm import BaseChatModel+ from browser_use.llm.views import ChatInvokeCompletion+ from browser_use.tools.service import Tools++ await _navigate(browser_session, f'{base_url}/products-table')++ captured_content: list[str] = []++ mock_llm = AsyncMock(spec=BaseChatModel)+ mock_llm.model = 'mock-llm'+ mock_llm._verified_api_keys = True+ mock_llm.provider = 'mock'+ mock_llm.name = 'mock-llm'+ mock_llm.model_name = 'mock-llm'++ async def capture_ainvoke(*args, **kwargs):+ if args:+ for msg in args[0]:+ content = getattr(msg, 'content', '')+ if isinstance(content, str):+ captured_content.append(content)+ elif isinstance(content, list):+ for part in content:+ if isinstance(part, dict) and part.get('type') == 'text':+ captured_content.append(part.get('text', ''))+ return ChatInvokeCompletion(completion='Widget A image: http://localhost/images/widget-a.jpg', usage=None)++ mock_llm.ainvoke.side_effect = capture_ainvoke++ tools = Tools()+ await tools.extract(+ query='get image url for each product',+ browser_session=browser_session,+ page_extraction_llm=mock_llm,+ file_system=FileSystem(base_dir='/tmp/test_extract_images'),+ )++ # The LLM should have received content that includes image markdown (td images with URLs)+ all_content = ' '.join(captured_content)+ assert '![' in all_content or 'widget-a.jpg' in all_content or 'widget-b.jpg' in all_content, (+ f'Expected image URLs in LLM input but got: {all_content[:500]}'+ )++ async def test_no_auto_detect_without_image_keyword(self, browser_session, base_url):+ """Query without image keywords does NOT auto-enable extract_images: table-cell img URLs absent."""+ from unittest.mock import AsyncMock++ from browser_use.filesystem.file_system import FileSystem+ from browser_use.llm import BaseChatModel+ from browser_use.llm.views import ChatInvokeCompletion+ from browser_use.tools.service import Tools++ await _navigate(browser_session, f'{base_url}/products-table')++ captured_content: list[str] = []++ mock_llm = AsyncMock(spec=BaseChatModel)+ mock_llm.model = 'mock-llm'+ mock_llm._verified_api_keys = True+ mock_llm.provider = 'mock'+ mock_llm.name = 'mock-llm'+ mock_llm.model_name = 'mock-llm'++ async def capture_ainvoke(*args, **kwargs):+ if args:+ for msg in args[0]:+ content = getattr(msg, 'content', '')+ if isinstance(content, str):+ captured_content.append(content)+ elif isinstance(content, list):+ for part in content:+ if isinstance(part, dict) and part.get('type') == 'text':+ captured_content.append(part.get('text', ''))+ return ChatInvokeCompletion(completion='Widget A - $29.99, Widget B - $49.99', usage=None)++ mock_llm.ainvoke.side_effect = capture_ainvoke++ tools = Tools()+ await tools.extract(+ query='get product names and prices',+ browser_session=browser_session,+ page_extraction_llm=mock_llm,+ file_system=FileSystem(base_dir='/tmp/test_extract_images'),+ )++ # Table-cell image URLs should NOT appear (extract_images=False, no auto-detect)+ all_content = ' '.join(captured_content)+ assert 'widget-a.jpg' not in all_content and 'widget-b.jpg' not in all_content, (+ f'Did not expect image URLs in LLM input but got: {all_content[:500]}'+ )diff --git a/tests/ci/test_search_find.py b/tests/ci/test_search_find.pyindex c4dfdf1fc..38afca2aa 100644--- a/tests/ci/test_search_find.py+++ b/tests/ci/test_search_find.py@@ -108,13 +108,28 @@ def http_server():content_type='text/html',)+ # /images-page route is registered dynamically in base_url fixture once port is knownyield serverserver.stop()@pytest.fixture(scope='session')def base_url(http_server):- return f'http://{http_server.host}:{http_server.port}'+ url = f'http://{http_server.host}:{http_server.port}'+ # Register images page here so we can embed the absolute img src URL+ http_server.expect_request('/images-page').respond_with_data(+ f"""+ <!DOCTYPE html>+ <html>+ <head><title>Images Page</title></head>+ <body>+ <img src="{url}/images/product.jpg" alt="Product">+ </body>+ </html>+ """,+ content_type='text/html',+ )+ return url@pytest.fixture(scope='module')@@ -407,6 +422,25 @@ class TestFindElements:assert result.extracted_content is not Noneassert 'No elements found' in result.extracted_content+ async def test_img_src_attribute_resolved(self, tools, browser_session, base_url):+ """find_elements with attributes=['src'] returns absolute URLs for img elements."""+ await _navigate_and_wait(tools, browser_session, f'{base_url}/images-page')++ result = await tools.find_elements(+ selector='img',+ attributes=['src'],+ browser_session=browser_session,+ )++ assert isinstance(result, ActionResult)+ assert result.error is None+ assert result.extracted_content is not None+ assert '1 element' in result.extracted_content+ assert 'src=' in result.extracted_content+ # The resolved DOM property should give the absolute URL (including the httpserver base URL)+ assert base_url in result.extracted_content+ assert 'product.jpg' in result.extracted_content+# --- Registration tests ---