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
disable screenshot clipping entirely for now
Nick Sweeting6170953b5e0c
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 480c21e43..828222016 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -25,7 +25,7 @@ os.environ['PW_TEST_SCREENSHOT_NO_FONTS_READY'] = '1' # https://github.com/micrimport anyioimport psutil-from playwright._impl._api_structures import FloatRect, ViewportSize+from playwright._impl._api_structures import ViewportSizefrom pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validatorfrom uuid_extensions import uuid7str@@ -725,7 +725,7 @@ class BrowserSession(BaseModel):full_page=False,# scale='css',timeout=self.browser_profile.default_timeout or 30000,- clip=FloatRect(**clip) if clip else None,+ # clip=FloatRect(**clip) if clip else None,animations='allow',caret='initial',)@@ -2726,40 +2726,16 @@ class BrowserSession(BaseModel):};}""")- # Calculate clip region that doesn't exceed page bounds- # The clip coordinates are in page coordinates, not viewport coordinates- clip_x = dimensions['scrollX']- clip_y = dimensions['scrollY']+ # When full_page=False, screenshot captures the current viewport+ # The clip parameter uses viewport coordinates (0,0 is top-left of viewport)+ # We just need to ensure the clip dimensions don't exceed our maximumsclip_width = min(dimensions['width'], MAX_SCREENSHOT_WIDTH)clip_height = min(dimensions['height'], MAX_SCREENSHOT_HEIGHT)- # Ensure clip region doesn't exceed page boundaries- max_x = max(0, dimensions['pageWidth'] - clip_x)- max_y = max(0, dimensions['pageHeight'] - clip_y)- clip_width = min(clip_width, max_x)- clip_height = min(clip_height, max_y)-- # Don't try to screenshot if the clip area would be empty- if clip_width <= 0 or clip_height <= 0:- self.logger.warning(- f'Screenshot clip area would be empty: width={clip_width}, height={clip_height}, scrollY={clip_y}, pageHeight={dimensions["pageHeight"]}'- )- # Fall back to capturing from top of viewport if we're scrolled past the page- clip_x = 0- clip_y = max(0, dimensions['pageHeight'] - dimensions['height'])- clip_width = min(dimensions['width'], MAX_SCREENSHOT_WIDTH, dimensions['pageWidth'])- clip_height = min(dimensions['height'], MAX_SCREENSHOT_HEIGHT, dimensions['pageHeight'] - clip_y)-# Take screenshot using our retry-decorated method- return await self._take_screenshot_hybrid(- page,- clip={- 'x': clip_x,- 'y': clip_y,- 'width': clip_width,- 'height': clip_height,- },- )+ # Don't pass clip parameter - let Playwright capture the full viewport+ # It will automatically handle cases where viewport extends beyond page content+ return await self._take_screenshot_hybrid(page)except Exception as e:self.logger.error(f'❌ Failed to take screenshot after retries: {type(e).__name__}: {e}')raisediff --git a/tests/ci/test_browser_session_screenshots.py b/tests/ci/test_browser_session_screenshots.pyindex b1c15c8c9..7c3428887 100644--- a/tests/ci/test_browser_session_screenshots.py+++ b/tests/ci/test_browser_session_screenshots.py@@ -2,6 +2,7 @@Test that screenshots work correctly in headless browser mode."""+import asyncioimport base64from browser_use.browser import BrowserProfile, BrowserSession@@ -244,3 +245,69 @@ class TestHeadlessScreenshots:for i, result in enumerate(results):if isinstance(result, Exception):print(f'Warning: Session {i} kill raised exception: {type(result).__name__}: {result}')++ async def test_screenshot_at_bottom_of_page(self, httpserver):+ """Test screenshot capture when scrolled to bottom of page (regression test for clipping issue)"""+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=False,+ )+ )++ try:+ await browser_session.start()++ # Create a page with scrollable content+ httpserver.expect_request('/scrollable').respond_with_data(+ """<html>+ <head><title>Scrollable Page Test</title></head>+ <body style="margin: 0; padding: 0;">+ <div style="height: 3000px; background: linear-gradient(to bottom, red, yellow, green, blue);">+ <div style="position: absolute; top: 0; left: 10px; font-size: 24px;">Top of page</div>+ <div style="position: absolute; top: 50%; left: 10px; font-size: 24px;">Middle of page</div>+ <div style="position: absolute; bottom: 10px; left: 10px; font-size: 24px;">Bottom of page</div>+ </div>+ </body>+ </html>""",+ content_type='text/html',+ )++ # Navigate to test page+ await browser_session.navigate(httpserver.url_for('/scrollable'))+ page = browser_session.agent_current_page+ assert page is not None++ # Test 1: Screenshot at top of page (should work)+ screenshot_top = await browser_session.take_screenshot()+ assert screenshot_top is not None+ assert len(base64.b64decode(screenshot_top)) > 5000++ # Test 2: Screenshot at middle of page+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight / 2)')+ await asyncio.sleep(0.1) # Wait for scroll+ screenshot_middle = await browser_session.take_screenshot()+ assert screenshot_middle is not None+ assert len(base64.b64decode(screenshot_middle)) > 5000++ # Test 3: Screenshot at bottom of page (this was failing with clipping error)+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight)')+ await asyncio.sleep(0.1) # Wait for scroll++ # This should not raise "Clipped area is either empty or outside the resulting image" error+ screenshot_bottom = await browser_session.take_screenshot()+ assert screenshot_bottom is not None+ assert len(base64.b64decode(screenshot_bottom)) > 5000++ # Test 4: Screenshot when scrolled beyond page bottom (edge case)+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight + 1000)')+ await asyncio.sleep(0.1)+ screenshot_beyond = await browser_session.take_screenshot()+ assert screenshot_beyond is not None+ assert len(base64.b64decode(screenshot_beyond)) > 5000++ print('✅ All screenshot positions tested successfully!')++ finally:+ await browser_session.stop()