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
Refactor scrolling logic in service.py to improve error handling and streamline element-specific scrolling. Removed commented-out code for accessibility tree retrieval and enhanced logging for debugging scroll attempts.
Magnus Müller225e5532dea5
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 216929e50..a91253d5d 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -428,32 +428,6 @@ Explain the content of the page and that the requested information is not availalogger.info(msg)raise RuntimeError(str(e))- # @self.registry.action(- # 'Get the accessibility tree of the page in the format "role name" with the number_of_elements to return',- # )- # async def get_ax_tree(number_of_elements: int, page: Page):- # node = await page.accessibility.snapshot(interesting_only=True)-- # def flatten_ax_tree(node, lines):- # if not node:- # return- # role = node.get('role', '')- # name = node.get('name', '')- # lines.append(f'{role} {name}')- # for child in node.get('children', []):- # flatten_ax_tree(child, lines)-- # lines = []- # flatten_ax_tree(node, lines)- # msg = '\n'.join(lines)- # logger.info(msg)- # return ActionResult(- # extracted_content=msg,- # include_in_memory=False,- # long_term_memory='Retrieved accessibility tree',- # include_extracted_content_only_once=True,- # )-@self.registry.action('Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). Optional index parameter to scroll within a specific element or its scroll container (works well for dropdowns and custom UI components).',param_model=ScrollAction,@@ -488,149 +462,129 @@ Explain the content of the page and that the requested information is not availa# Initialize result message componentsdirection = 'down' if params.down else 'up'scroll_target = 'the page'- pages_text = f'{pages_scrolled} pages' if pages_scrolled != 1.0 else 'one page'# Element-specific scrolling if index is providedif params.index is not None:try:- # Check if element exists in current selector map- selector_map = await browser_session.get_selector_map()- element_node = None # Initialize to avoid undefined variable-- if params.index not in selector_map:- # Force a state refresh in case the cache is stale- logger.info(f'Element with index {params.index} not found in selector map, refreshing state...')- await browser_session.get_state_summary(cache_clickable_elements_hashes=True)- selector_map = await browser_session.get_selector_map()-- if params.index not in selector_map:- # Return informative message about invalid index- max_index = max(selector_map.keys()) if selector_map else -1- msg = f'❌ Element with index {params.index} does not exist. Page has {len(selector_map)} interactive elements (indices 0-{max_index}). Using page-level scroll instead.'- logger.warning(msg)- scroll_target = 'the page'- # Skip element-specific scrolling- else:- element_node = await browser_session.get_dom_element_by_index(params.index)- else:- element_node = await browser_session.get_dom_element_by_index(params.index)-- if element_node is not None and params.index in selector_map:- # Try direct container scrolling (no events that might close dropdowns)- container_scroll_js = """- (params) => {- const { dy, elementXPath } = params;-- // Get the target element by XPath- const targetElement = document.evaluate(elementXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;- if (!targetElement) {- return { success: false, reason: 'Element not found by XPath' };- }+ element_node = await browser_session.get_dom_element_by_index(params.index)+ if element_node is None:+ raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')++ # Try direct container scrolling (no events that might close dropdowns)+ container_scroll_js = """+ (params) => {+ const { dy, elementXPath } = params;++ // Get the target element by XPath+ const targetElement = document.evaluate(elementXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;+ if (!targetElement) {+ return { success: false, reason: 'Element not found by XPath' };+ }- console.log('[SCROLL DEBUG] Starting direct container scroll for element:', targetElement.tagName);+ console.log('[SCROLL DEBUG] Starting direct container scroll for element:', targetElement.tagName);++ // Try to find scrollable containers in the hierarchy (starting from element itself)+ let currentElement = targetElement;+ let scrollSuccess = false;+ let scrolledElement = null;+ let scrollDelta = 0;+ let attempts = 0;++ // Check up to 10 elements in hierarchy (including the target element itself)+ while (currentElement && attempts < 10) {+ const computedStyle = window.getComputedStyle(currentElement);+ const hasScrollableY = /(auto|scroll|overlay)/.test(computedStyle.overflowY);+ const canScrollVertically = currentElement.scrollHeight > currentElement.clientHeight;- // Try to find scrollable containers in the hierarchy (starting from element itself)- let currentElement = targetElement;- let scrollSuccess = false;- let scrolledElement = null;- let scrollDelta = 0;- let attempts = 0;+ console.log('[SCROLL DEBUG] Checking element:', currentElement.tagName,+ 'hasScrollableY:', hasScrollableY,+ 'canScrollVertically:', canScrollVertically,+ 'scrollHeight:', currentElement.scrollHeight,+ 'clientHeight:', currentElement.clientHeight);- // Check up to 10 elements in hierarchy (including the target element itself)- while (currentElement && attempts < 10) {- const computedStyle = window.getComputedStyle(currentElement);- const hasScrollableY = /(auto|scroll|overlay)/.test(computedStyle.overflowY);- const canScrollVertically = currentElement.scrollHeight > currentElement.clientHeight;+ if (hasScrollableY && canScrollVertically) {+ const beforeScroll = currentElement.scrollTop;+ const maxScroll = currentElement.scrollHeight - currentElement.clientHeight;- console.log('[SCROLL DEBUG] Checking element:', currentElement.tagName,- 'hasScrollableY:', hasScrollableY,- 'canScrollVertically:', canScrollVertically,- 'scrollHeight:', currentElement.scrollHeight,- 'clientHeight:', currentElement.clientHeight);+ // Calculate scroll amount (1/3 of provided dy for gentler scrolling)+ let scrollAmount = dy / 3;- if (hasScrollableY && canScrollVertically) {- const beforeScroll = currentElement.scrollTop;- const maxScroll = currentElement.scrollHeight - currentElement.clientHeight;-- // Calculate scroll amount (1/3 of provided dy for gentler scrolling)- let scrollAmount = dy / 3;-- // Ensure we don't scroll beyond bounds- if (scrollAmount > 0) {- scrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll);- } else {- scrollAmount = Math.max(scrollAmount, -beforeScroll);- }-- // Try direct scrollTop manipulation (most reliable)- currentElement.scrollTop = beforeScroll + scrollAmount;-- const afterScroll = currentElement.scrollTop;- const actualScrollDelta = afterScroll - beforeScroll;-- console.log('[SCROLL DEBUG] Scroll attempt:', currentElement.tagName,- 'before:', beforeScroll, 'after:', afterScroll, 'delta:', actualScrollDelta);-- if (Math.abs(actualScrollDelta) > 0.5) {- scrollSuccess = true;- scrolledElement = currentElement;- scrollDelta = actualScrollDelta;- console.log('[SCROLL DEBUG] Successfully scrolled container:', currentElement.tagName, 'delta:', actualScrollDelta);- break;- }+ // Ensure we don't scroll beyond bounds+ if (scrollAmount > 0) {+ scrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll);+ } else {+ scrollAmount = Math.max(scrollAmount, -beforeScroll);}- // Move to parent (but don't go beyond body for dropdown case)- if (currentElement === document.body || currentElement === document.documentElement) {+ // Try direct scrollTop manipulation (most reliable)+ currentElement.scrollTop = beforeScroll + scrollAmount;++ const afterScroll = currentElement.scrollTop;+ const actualScrollDelta = afterScroll - beforeScroll;++ console.log('[SCROLL DEBUG] Scroll attempt:', currentElement.tagName,+ 'before:', beforeScroll, 'after:', afterScroll, 'delta:', actualScrollDelta);++ if (Math.abs(actualScrollDelta) > 0.5) {+ scrollSuccess = true;+ scrolledElement = currentElement;+ scrollDelta = actualScrollDelta;+ console.log('[SCROLL DEBUG] Successfully scrolled container:', currentElement.tagName, 'delta:', actualScrollDelta);break;}- currentElement = currentElement.parentElement;- attempts++;}- if (scrollSuccess) {- // Successfully scrolled a container- return {- success: true,- method: 'direct_container_scroll',- containerType: 'element',- containerTag: scrolledElement.tagName.toLowerCase(),- containerClass: scrolledElement.className || '',- containerId: scrolledElement.id || '',- scrollDelta: scrollDelta- };- } else {- // No container found or could scroll- console.log('[SCROLL DEBUG] No scrollable container found for element');- return {- success: false,- reason: 'No scrollable container found',- needsPageScroll: true- };+ // Move to parent (but don't go beyond body for dropdown case)+ if (currentElement === document.body || currentElement === document.documentElement) {+ break;}+ currentElement = currentElement.parentElement;+ attempts++;}- """-- # Pass parameters as a single object- scroll_params = {'dy': dy, 'elementXPath': element_node.xpath}- result = await page.evaluate(container_scroll_js, scroll_params)-- if result['success']:- if result['containerType'] == 'element':- container_info = f'{result["containerTag"]}'- if result['containerId']:- container_info += f'#{result["containerId"]}'- elif result['containerClass']:- container_info += f'.{result["containerClass"].split()[0]}'- scroll_target = f"element {params.index}'s scroll container ({container_info})"- # Don't do additional page scrolling since we successfully scrolled the container- else:- scroll_target = f'the page (fallback from element {params.index})'++ if (scrollSuccess) {+ // Successfully scrolled a container+ return {+ success: true,+ method: 'direct_container_scroll',+ containerType: 'element',+ containerTag: scrolledElement.tagName.toLowerCase(),+ containerClass: scrolledElement.className || '',+ containerId: scrolledElement.id || '',+ scrollDelta: scrollDelta+ };+ } else {+ // No container found or could scroll+ console.log('[SCROLL DEBUG] No scrollable container found for element');+ return {+ success: false,+ reason: 'No scrollable container found',+ needsPageScroll: true+ };+ }+ }+ """++ # Pass parameters as a single object+ scroll_params = {'dy': dy, 'elementXPath': element_node.xpath}+ result = await page.evaluate(container_scroll_js, scroll_params)++ if result['success']:+ if result['containerType'] == 'element':+ container_info = f'{result["containerTag"]}'+ if result['containerId']:+ container_info += f'#{result["containerId"]}'+ elif result['containerClass']:+ container_info += f'.{result["containerClass"].split()[0]}'+ scroll_target = f"element {params.index}'s scroll container ({container_info})"+ # Don't do additional page scrolling since we successfully scrolled the containerelse:- # Container scroll failed, need page-level scrolling- logger.debug(f'Container scroll failed for element {params.index}: {result.get("reason", "Unknown")}')- scroll_target = f'the page (no container found for element {params.index})'- # This will trigger page-level scrolling below+ scroll_target = f'the page (fallback from element {params.index})'+ else:+ # Container scroll failed, need page-level scrolling+ logger.debug(f'Container scroll failed for element {params.index}: {result.get("reason", "Unknown")}')+ scroll_target = f'the page (no container found for element {params.index})'+ # This will trigger page-level scrolling belowexcept Exception as e:logger.debug(f'Element-specific scrolling failed for index {params.index}: {e}')@@ -663,8 +617,6 @@ Explain the content of the page and that the requested information is not availalogger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=long_term_memory)- # send keys-@self.registry.action('Send strings of special keys to use Playwright page.keyboard.press - examples include Escape, Backspace, Insert, PageDown, Delete, Enter, or Shortcuts such as `Control+o`, `Control+Shift+T`',param_model=SendKeysAction,