Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

make wait_for_load_state and network errors into AgentState entries instead of hard exceptions

Nick Sweeting688b4768e258
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 46c9b5969..2eb2413b8 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -443,10 +443,10 @@ class BrowserSession(BaseModel):
await self.playwright.stop()
# Give playwright tasks a moment to clean up properly
# This prevents "Task was destroyed but it is pending!" warnings
- await asyncio.sleep(0.01)
+ await asyncio.sleep(0.1)
# self.logger.debug('🎭 Stopped playwright node.js API worker')
except Exception as e:
- self.logger.warning(f'❌ Error stopping playwright: {type(e).__name__}: {e}')
+ self.logger.warning(f'❌ Error stopping playwright node.js API subprocess: {type(e).__name__}: {e}')
finally:
# Clear global references if they match this instance
global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT
@@ -1457,12 +1457,18 @@ class BrowserSession(BaseModel):
except Exception:
# If no download is triggered, treat as normal click
# self.logger.debug('No download triggered within timeout. Checking navigation...')
- await page.wait_for_load_state()
+ try:
+ await page.wait_for_load_state()
+ except Exception as e:
+ self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}')
await self._check_and_handle_navigation(page)
else:
# If downloads are disabled, just perform the click
await click_func()
- await page.wait_for_load_state()
+ try:
+ await page.wait_for_load_state()
+ except Exception as e:
+ self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}')
await self._check_and_handle_navigation(page)
try:
@@ -1499,7 +1505,10 @@ class BrowserSession(BaseModel):
await page.mouse.click(
element_node.viewport_coordinates.center.x, element_node.viewport_coordinates.center.y
)
- await page.wait_for_load_state()
+ try:
+ await page.wait_for_load_state()
+ except Exception:
+ pass
await self._check_and_handle_navigation(page)
return None # Success
except Exception as coord_e:
@@ -2061,14 +2070,20 @@ class BrowserSession(BaseModel):
page = await self.get_current_page()
await page.goto(url)
- await page.wait_for_load_state()
+ try:
+ await page.wait_for_load_state()
+ except Exception as e:
+ self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to fully load after navigation: {type(e).__name__}: {e}')
async def refresh_page(self):
"""Refresh the agent's current page"""
page = await self.get_current_page()
await page.reload()
- await page.wait_for_load_state()
+ try:
+ await page.wait_for_load_state()
+ except Exception as e:
+ self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to fully load after refresh: {type(e).__name__}: {e}')
async def go_back(self):
"""Navigate the agent's tab back in browser history"""
@@ -2332,7 +2347,7 @@ class BrowserSession(BaseModel):
full_page=full_page,
scale='css',
timeout=15000,
- animations='disabled',
+ animations='allow',
caret='initial',
)
@@ -2372,8 +2387,9 @@ class BrowserSession(BaseModel):
scale='css',
timeout=30000,
clip={'x': 0, 'y': 0, 'width': expanded_width, 'height': expanded_height},
+ animations='allow',
+ caret='initial',
# animations='disabled', # these can cause CSP errors on some pages, leading to a red herring "waiting for fonts to load" error
- # caret='initial',
)
# TODO: manually take multiple clipped screenshots to capture the full height and stitch them together?
@@ -2814,6 +2830,7 @@ class BrowserSession(BaseModel):
# update the human's active tab to match the agent's
if self.human_current_page != page:
# TODO: figure out how to do this without bringing the entire window to the foreground and stealing foreground app focus
+ # might require browser-use extension loaded into the browser so we can use chrome.tabs extension APIs
await page.bring_to_front()
self.human_current_page = page
@@ -2859,7 +2876,11 @@ class BrowserSession(BaseModel):
if (not self.human_current_page) or self.human_current_page.is_closed():
self.human_current_page = new_page
- await new_page.wait_for_load_state()
+ tab_idx = self.tabs.index(new_page)
+ try:
+ await new_page.wait_for_load_state()
+ except Exception as e:
+ self.logger.warning(f'⚠️ New page [{tab_idx}]{_log_pretty_url(new_page.url)} failed to fully load: {type(e).__name__}: {e}')
# Set the viewport size for the new tab
if self.browser_profile.viewport:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 26ae00991..254ee61fc 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -98,15 +98,26 @@ class Controller(Generic[Context]):
@self.registry.action('Navigate to URL in the current tab', param_model=GoToUrlAction)
async def go_to_url(params: GoToUrlAction, browser_session: BrowserSession):
- page = await browser_session.get_current_page()
- if page:
- await page.goto(params.url)
- await page.wait_for_load_state()
- else:
- page = await browser_session.create_new_tab(params.url)
- msg = f'πŸ”— Navigated to {params.url}'
- logger.info(msg)
- return ActionResult(extracted_content=msg, include_in_memory=True)
+ try:
+ page = await browser_session.get_current_page()
+ if page:
+ await page.goto(params.url)
+ await page.wait_for_load_state()
+ else:
+ page = await browser_session.create_new_tab(params.url)
+ msg = f'πŸ”— Navigated to {params.url}'
+ logger.info(msg)
+ return ActionResult(extracted_content=msg, include_in_memory=True)
+ except Exception as e:
+ error_msg = str(e)
+ # Check for network-related errors
+ if any(err in error_msg for err in ['ERR_NAME_NOT_RESOLVED', 'ERR_INTERNET_DISCONNECTED', 'ERR_CONNECTION_REFUSED', 'ERR_TIMED_OUT', 'net::']):
+ site_unavailable_msg = f'Site unavailable: {params.url} - {error_msg}'
+ logger.warning(site_unavailable_msg)
+ return ActionResult(success=False, error=site_unavailable_msg, include_in_memory=True)
+ else:
+ # Re-raise non-network errors
+ raise
@self.registry.action('Go back', param_model=NoParamsAction)
async def go_back(params: NoParamsAction, browser_session: BrowserSession):
@@ -172,7 +183,7 @@ class Controller(Generic[Context]):
msg += f' - {new_tab_msg}'
logger.info(new_tab_msg)
await browser_session.switch_to_tab(-1)
- return ActionResult(extracted_content=msg, include_in_memory=True)
+ return ActionResult(extracted_content=msg, include_in_memory=True, success=True)
except Exception as e:
error_msg = str(e)
if 'Execution context was destroyed' in error_msg or 'Cannot find context with specified id' in error_msg:
@@ -221,17 +232,21 @@ class Controller(Generic[Context]):
@self.registry.action('Switch tab', param_model=SwitchTabAction)
async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):
await browser_session.switch_to_tab(params.page_id)
- # Wait for tab to be ready and ensure references are synchronized
page = await browser_session.get_current_page()
- await page.wait_for_load_state()
- msg = f'πŸ”„ Switched to tab {params.page_id}'
+ try:
+ await page.wait_for_load_state(state='domcontentloaded', timeout=5_000)
+ # page was already loaded when we first navigated, this is additional to wait for onfocus/onblur animations/ajax to settle
+ except Exception as e:
+ pass
+ msg = f'πŸ”„ Switched to tab #{params.page_id} with url {page.url}'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action('Open a specific url in new tab', param_model=OpenTabAction)
async def open_tab(params: OpenTabAction, browser_session: BrowserSession):
- await browser_session.create_new_tab(params.url)
- msg = f'πŸ”— Opened new tab with {params.url}'
+ page = await browser_session.create_new_tab(params.url)
+ tab_idx = browser_session.tabs.index(page)
+ msg = f'πŸ”— Opened new tab #{tab_idx} with url {params.url}'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)