Skip to content

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

linter fixes

Nick Sweetinga1f1330aa6d1
diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.py
index 6f5aada2c..b5b04b001 100644
--- a/browser_use/browser/storage_state_watchdog.py
+++ b/browser_use/browser/storage_state_watchdog.py
@@ -326,5 +326,3 @@ class StorageStateWatchdog(BaseWatchdog):
self.logger.info(f'[StorageStateWatchdog] Added {len(cookies)} cookies')
except Exception as e:
self.logger.error(f'[StorageStateWatchdog] Failed to add cookies: {e}')
-
-
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 890f4181a..c83b37578 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -274,7 +274,9 @@ class Controller(Generic[Context]):
# Dispatch type text event with node
try:
- event = browser_session.event_bus.dispatch(TypeTextEvent(node=node, text=params.text, clear_existing=params.clear_existing))
+ event = browser_session.event_bus.dispatch(
+ TypeTextEvent(node=node, text=params.text, clear_existing=params.clear_existing)
+ )
await event
await event.event_result(raise_if_any=True, raise_if_none=False)
msg = f"Input '{params.text}' into element {params.index}."
@@ -600,7 +602,11 @@ Provide the extracted information in a clear, structured format."""
direction = 'down' if params.down else 'up'
# If index is 0 or None, we're scrolling the page
- target = 'the page' if params.frame_element_index is None or params.frame_element_index == 0 else f'element {params.frame_element_index}'
+ target = (
+ 'the page'
+ if params.frame_element_index is None or params.frame_element_index == 0
+ else f'element {params.frame_element_index}'
+ )
if params.num_pages == 1.0:
long_term_memory = f'Scrolled {direction} {target} by one page'
diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.py
index 1936ed309..e5600c882 100644
--- a/browser_use/dom/playground/tree.py
+++ b/browser_use/dom/playground/tree.py
@@ -35,9 +35,12 @@ async def main():
# await browser.create_new_tab('https://semantic-ui.com/modules/dropdown.html#/definition')
# await browser.navigate('https://v0-website-with-clickable-elements.vercel.app/iframe-buttons')
from browser_use.browser.events import NavigateToUrlEvent
- nav_event = browser.event_bus.dispatch(NavigateToUrlEvent(url='https://v0-website-with-clickable-elements.vercel.app/nested-iframe'))
+
+ nav_event = browser.event_bus.dispatch(
+ NavigateToUrlEvent(url='https://v0-website-with-clickable-elements.vercel.app/nested-iframe')
+ )
await nav_event
-
+
# Wait a moment for page to fully load
await asyncio.sleep(2)
@@ -55,7 +58,7 @@ async def main():
if not targets:
raise ValueError('No targets available')
target_id = targets[0]['targetId']
-
+
result = await dom_service.get_dom_tree(target_id)
if isinstance(result, tuple):
dom_tree = result[0]
diff --git a/browser_use/dom/serializer/clickable_elements.py b/browser_use/dom/serializer/clickable_elements.py
index 068bbdf50..836dba8ca 100644
--- a/browser_use/dom/serializer/clickable_elements.py
+++ b/browser_use/dom/serializer/clickable_elements.py
@@ -17,7 +17,7 @@ class ClickableElementDetector:
# remove html and body nodes
if node.tag_name in {'html', 'body'}:
return False
-
+
# IFRAME elements should be interactive if they're large enough to potentially need scrolling
# Small iframes (< 100px width or height) are unlikely to have scrollable content
if node.tag_name and node.tag_name.upper() == 'IFRAME':
@@ -109,7 +109,7 @@ class ClickableElementDetector:
}
if node.tag_name in interactive_tags:
return True
-
+
# SVG elements need special handling - only interactive if they have explicit handlers
# svg_tags = {'svg', 'path', 'circle', 'rect', 'polygon', 'ellipse', 'line', 'polyline', 'g'}
# if node.tag_name in svg_tags:
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index c31bccc8e..a899d713a 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -208,18 +208,18 @@ class DomService:
# The scrollRects represent the current scroll position
# The clientRects represent the viewport size
# Elements are visible if they fall within the viewport after accounting for scroll
-
+
# The viewport of the frame (what's actually visible)
viewport_left = 0 # Viewport always starts at 0 in frame coordinates
viewport_top = 0
viewport_right = frame.snapshot_node.clientRects.width
viewport_bottom = frame.snapshot_node.clientRects.height
-
+
# Adjust element bounds by the scroll offset to get position relative to viewport
# When scrolled down, scrollRects.y is positive, so we subtract it from element's y
adjusted_x = current_bounds.x - frame.snapshot_node.scrollRects.x
adjusted_y = current_bounds.y - frame.snapshot_node.scrollRects.y
-
+
frame_intersects = (
adjusted_x < viewport_right
and adjusted_x + current_bounds.width > viewport_left
@@ -233,11 +233,19 @@ class DomService:
attrs = node.attributes
elem_id = attrs.get('id', '')
elem_name = attrs.get('name', '')
- if 'city' in elem_id.lower() or 'city' in elem_name.lower() or \
- 'state' in elem_id.lower() or 'state' in elem_name.lower() or \
- 'zip' in elem_id.lower() or 'zip' in elem_name.lower():
+ if (
+ 'city' in elem_id.lower()
+ or 'city' in elem_name.lower()
+ or 'state' in elem_id.lower()
+ or 'state' in elem_name.lower()
+ or 'zip' in elem_id.lower()
+ or 'zip' in elem_name.lower()
+ ):
import logging
- logging.info(f"πŸ” DEBUG: Element id='{elem_id}' name='{elem_name}' not visible - adjusted bounds: x={adjusted_x}, y={adjusted_y}, w={current_bounds.width}, h={current_bounds.height}, viewport: {viewport_right}x{viewport_bottom}, scroll: x={frame.snapshot_node.scrollRects.x}, y={frame.snapshot_node.scrollRects.y}")
+
+ logging.info(
+ f"πŸ” DEBUG: Element id='{elem_id}' name='{elem_name}' not visible - adjusted bounds: x={adjusted_x}, y={adjusted_y}, w={current_bounds.width}, h={current_bounds.height}, viewport: {viewport_right}x{viewport_bottom}, scroll: x={frame.snapshot_node.scrollRects.x}, y={frame.snapshot_node.scrollRects.y}"
+ )
return False
# Keep the original coordinate adjustment to maintain consistency
@@ -296,8 +304,8 @@ class DomService:
except Exception as e:
pass # Page might not be ready yet
# DEBUG: Log before capturing snapshot
- self.logger.info(f"πŸ” DEBUG: Capturing DOM snapshot for target {target_id}")
-
+ self.logger.info(f'πŸ” DEBUG: Capturing DOM snapshot for target {target_id}')
+
# Get actual scroll positions for all iframes before capturing snapshot
iframe_scroll_positions = {}
try:
@@ -323,17 +331,19 @@ class DomService:
return scrollData;
})()
""",
- 'returnByValue': True
- },
- session_id=cdp_session.session_id
+ 'returnByValue': True,
+ },
+ session_id=cdp_session.session_id,
)
if scroll_result and 'result' in scroll_result and 'value' in scroll_result['result']:
iframe_scroll_positions = scroll_result['result']['value']
for idx, scroll_data in iframe_scroll_positions.items():
- self.logger.info(f"πŸ” DEBUG: Iframe {idx} actual scroll position - scrollTop={scroll_data.get('scrollTop', 0)}, scrollLeft={scroll_data.get('scrollLeft', 0)}")
+ self.logger.info(
+ f'πŸ” DEBUG: Iframe {idx} actual scroll position - scrollTop={scroll_data.get("scrollTop", 0)}, scrollLeft={scroll_data.get("scrollLeft", 0)}'
+ )
except Exception as e:
- self.logger.debug(f"Failed to get iframe scroll positions: {e}")
-
+ self.logger.debug(f'Failed to get iframe scroll positions: {e}')
+
snapshot_request = cdp_session.cdp_client.send.DOMSnapshot.captureSnapshot(
params={
'computedStyles': REQUIRED_COMPUTED_STYLES,
@@ -367,15 +377,15 @@ class DomService:
device_pixel_ratio = await asyncio.wait_for(device_pixel_ratio_request, timeout=2.0)
end = time.time()
cdp_timing = {'cdp_calls_total': end - start}
-
+
# DEBUG: Log snapshot info
if snapshot and 'documents' in snapshot:
total_nodes = sum(len(doc.get('nodes', [])) for doc in snapshot['documents'])
- self.logger.info(f"πŸ” DEBUG: Snapshot contains {len(snapshot['documents'])} documents with {total_nodes} total nodes")
+ self.logger.info(f'πŸ” DEBUG: Snapshot contains {len(snapshot["documents"])} documents with {total_nodes} total nodes')
# Log iframe-specific info
for doc_idx, doc in enumerate(snapshot['documents']):
if doc_idx > 0: # Not the main document
- self.logger.info(f"πŸ” DEBUG: Document {doc_idx} has {len(doc.get('nodes', []))} nodes")
+ self.logger.info(f'πŸ” DEBUG: Document {doc_idx} has {len(doc.get("nodes", []))} nodes')
return TargetAllTrees(
snapshot=snapshot,
@@ -515,7 +525,9 @@ class DomService:
total_frame_offset.x -= snapshot_data.scrollRects.x
total_frame_offset.y -= snapshot_data.scrollRects.y
# DEBUG: Log iframe scroll information
- self.logger.info(f"πŸ” DEBUG: HTML frame scroll - scrollY={snapshot_data.scrollRects.y}, scrollX={snapshot_data.scrollRects.x}, frameId={node.get('frameId')}, nodeId={node['nodeId']}")
+ self.logger.info(
+ f'πŸ” DEBUG: HTML frame scroll - scrollY={snapshot_data.scrollRects.y}, scrollX={snapshot_data.scrollRects.x}, frameId={node.get("frameId")}, nodeId={node["nodeId"]}'
+ )
# Calculate new iframe offset for content documents, accounting for iframe scroll
if node['nodeName'].upper() == 'IFRAME' and snapshot_data and snapshot_data.bounds:
@@ -549,16 +561,23 @@ class DomService:
# Set visibility using the collected HTML frames
dom_tree_node.is_visible = self.is_element_visible_according_to_all_parents(dom_tree_node, updated_html_frames)
-
+
# DEBUG: Log visibility info for form elements in iframes
if dom_tree_node.tag_name and dom_tree_node.tag_name.upper() in ['INPUT', 'SELECT', 'TEXTAREA', 'LABEL']:
attrs = dom_tree_node.attributes or {}
elem_id = attrs.get('id', '')
elem_name = attrs.get('name', '')
- if 'city' in elem_id.lower() or 'city' in elem_name.lower() or \
- 'state' in elem_id.lower() or 'state' in elem_name.lower() or \
- 'zip' in elem_id.lower() or 'zip' in elem_name.lower():
- self.logger.info(f"πŸ” DEBUG: Form element {dom_tree_node.tag_name} id='{elem_id}' name='{elem_name}' - visible={dom_tree_node.is_visible}, bounds={dom_tree_node.snapshot_node.bounds if dom_tree_node.snapshot_node else 'NO_SNAPSHOT'}")
+ if (
+ 'city' in elem_id.lower()
+ or 'city' in elem_name.lower()
+ or 'state' in elem_id.lower()
+ or 'state' in elem_name.lower()
+ or 'zip' in elem_id.lower()
+ or 'zip' in elem_name.lower()
+ ):
+ self.logger.info(
+ f"πŸ” DEBUG: Form element {dom_tree_node.tag_name} id='{elem_id}' name='{elem_name}' - visible={dom_tree_node.is_visible}, bounds={dom_tree_node.snapshot_node.bounds if dom_tree_node.snapshot_node else 'NO_SNAPSHOT'}"
+ )
# handle cross origin iframe (just recursively call the main function with the proper target if it exists in iframes)
# only do this if the iframe is visible (otherwise it's not worth it)
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index ced8f5485..9f852160a 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -218,7 +218,7 @@ class FIFOHandler(logging.Handler):
if self.fd is not None:
try:
os.close(self.fd)
- except:
+ except Exception:
pass
self.fd = None
@@ -226,12 +226,12 @@ class FIFOHandler(logging.Handler):
if hasattr(self, 'fd') and self.fd is not None:
try:
os.close(self.fd)
- except:
+ except Exception:
pass
super().close()
-def setup_log_pipes(session_id: str, base_dir: str = None):
+def setup_log_pipes(session_id: str, base_dir: str | None = None):
"""Setup named pipes for log streaming.
Usage:
diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.py
index 8d56d46a1..a2060e197 100644
--- a/examples/custom-functions/action_filters.py
+++ b/examples/custom-functions/action_filters.py
@@ -52,7 +52,7 @@ async def disco_mode(browser_session: BrowserSession):
});
})()"""
},
- session_id=cdp_session.session_id
+ session_id=cdp_session.session_id,
)
@@ -63,12 +63,11 @@ async def is_login_page(browser_session: BrowserSession) -> bool:
# Get current URL using CDP
cdp_session = await browser_session.get_or_create_cdp_session()
result = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': 'window.location.href', 'returnByValue': True},
- session_id=cdp_session.session_id
+ params={'expression': 'window.location.href', 'returnByValue': True}, session_id=cdp_session.session_id
)
url = result.get('result', {}).get('value', '')
return 'login' in url.lower() or 'signin' in url.lower()
- except:
+ except Exception:
return False
@@ -79,7 +78,7 @@ async def use_the_force(browser_session: BrowserSession):
# Check if it's a login page
if not await is_login_page(browser_session):
return # Skip if not a login page
-
+
# Execute JavaScript using CDP
cdp_session = await browser_session.get_or_create_cdp_session()
await cdp_session.cdp_client.send.Runtime.evaluate(
@@ -88,7 +87,7 @@ async def use_the_force(browser_session: BrowserSession):
document.querySelector('body').innerHTML = 'These are not the droids you are looking for';
})()"""
},
- session_id=cdp_session.session_id
+ session_id=cdp_session.session_id,
)
@@ -118,4 +117,4 @@ async def main():
if __name__ == '__main__':
- asyncio.run(main())
\ No newline at end of file
+ asyncio.run(main())
diff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.py
index 2c9aad689..9bce8b846 100644
--- a/examples/custom-functions/hover_element.py
+++ b/examples/custom-functions/hover_element.py
@@ -7,7 +7,6 @@ This shows how to hover over elements to trigger hover states and tooltips.
import asyncio
import os
import sys
-from typing import Optional
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -27,9 +26,10 @@ controller = Controller()
class HoverAction(BaseModel):
"""Parameters for hover action"""
- index: Optional[int] = None
- xpath: Optional[str] = None
- selector: Optional[str] = None
+
+ index: int | None = None
+ xpath: str | None = None
+ selector: str | None = None
@controller.registry.action(
@@ -42,7 +42,7 @@ async def hover_element(params: HoverAction, browser_session: BrowserSession):
"""
try:
element_node = None
-
+
if params.xpath:
# Find element by XPath using CDP
cdp_session = await browser_session.get_or_create_cdp_session()
@@ -58,15 +58,15 @@ async def hover_element(params: HoverAction, browser_session: BrowserSession):
return {{found: false}};
}})()
""",
- 'returnByValue': True
+ 'returnByValue': True,
},
- session_id=cdp_session.session_id
+ session_id=cdp_session.session_id,
)
element_info = result.get('result', {}).get('value', {})
if not element_info.get('found'):
raise Exception(f'Failed to locate element with XPath {params.xpath}')
x, y = element_info['x'], element_info['y']
-
+
elif params.selector:
# Find element by CSS selector using CDP
cdp_session = await browser_session.get_or_create_cdp_session()
@@ -82,35 +82,35 @@ async def hover_element(params: HoverAction, browser_session: BrowserSession):
return {{found: false}};
}})()
""",
- 'returnByValue': True
+ 'returnByValue': True,
},
- session_id=cdp_session.session_id
+ session_id=cdp_session.session_id,
)
element_info = result.get('result', {}).get('value', {})
if not element_info.get('found'):
raise Exception(f'Failed to locate element with CSS Selector {params.selector}')
x, y = element_info['x'], element_info['y']
-
+
elif params.index is not None:
# Use index to locate the element
selector_map = await browser_session.get_selector_map()
if params.index not in selector_map:
raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')
element_node = selector_map[params.index]
-
+
# Get element position
if not element_node.absolute_position:
raise Exception(f'Element at index {params.index} has no position information')
-
+
x = element_node.absolute_position.x + element_node.absolute_position.width / 2
y = element_node.absolute_position.y + element_node.absolute_position.height / 2
-
+
else:
raise Exception('Either index, xpath, or selector must be provided')
# Perform hover using CDP mouse events
cdp_session = await browser_session.get_or_create_cdp_session()
-
+
# Move mouse to the element position
await cdp_session.cdp_client.send.Input.dispatchMouseEvent(
params={
@@ -118,12 +118,12 @@ async def hover_element(params: HoverAction, browser_session: BrowserSession):
'x': x,
'y': y,
},
- session_id=cdp_session.session_id
+ session_id=cdp_session.session_id,
)
-
+
# Wait a bit for hover state to trigger
await asyncio.sleep(0.1)
-
+
msg = (
f'πŸ–±οΈ Hovered over element at index {params.index}'
if params.index is not None
@@ -132,7 +132,7 @@ async def hover_element(params: HoverAction, browser_session: BrowserSession):
else f'πŸ–±οΈ Hovered over element with selector {params.selector}'
)
return ActionResult(extracted_content=msg, include_in_memory=True)
-
+
except Exception as e:
error_msg = f'❌ Failed to hover over element: {str(e)}'
return ActionResult(error=error_msg)
@@ -164,4 +164,4 @@ async def main():
if __name__ == '__main__':
- asyncio.run(main())
\ No newline at end of file
+ asyncio.run(main())
diff --git a/examples/features/multiple_tasks.py b/examples/features/multiple_tasks.py
index 1fade4e12..0da02d666 100644
--- a/examples/features/multiple_tasks.py
+++ b/examples/features/multiple_tasks.py
@@ -10,7 +10,8 @@ load_dotenv()
from browser_use import Agent
-from browser_use.browser import BrowserSession, BrowserProfile
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser.profile import ViewportSize
from browser_use.llm import ChatGoogle
api_key = os.getenv('GOOGLE_API_KEY')
@@ -25,15 +26,15 @@ async def main():
# Create browser profile with settings
browser_profile = BrowserProfile(
headless=False,
- viewport={'width': 1502, 'height': 853},
+ viewport=ViewportSize(width=1502, height=853),
ignore_https_errors=True,
)
-
+
# Create browser session
browser_session = BrowserSession(
browser_profile=browser_profile,
)
-
+
# Start the browser
await browser_session.start()
@@ -43,40 +44,40 @@ async def main():
llm=llm,
)
- try:
- result = await agent.run()
- print(f'First task was {"successful" if result.is_successful else "not successful"}')
+ try:
+ result = await agent.run()
+ print(f'First task was {"successful" if result.is_successful else "not successful"}')
- if not result.is_successful:
- raise RuntimeError('Failed to navigate to the initial page.')
+ if not result.is_successful:
+ raise RuntimeError('Failed to navigate to the initial page.')
- agent.add_new_task('Navigate to the documentation page')
+ agent.add_new_task('Navigate to the documentation page')
- result = await agent.run()
- print(f'Second task was {"successful" if result.is_successful else "not successful"}')
+ result = await agent.run()
+ print(f'Second task was {"successful" if result.is_successful else "not successful"}')
- if not result.is_successful:
- raise RuntimeError('Failed to navigate to the documentation page.')
+ if not result.is_successful:
+ raise RuntimeError('Failed to navigate to the documentation page.')
- while True:
- next_task = input('Write your next task or leave empty to exit\n> ')
+ while True:
+ next_task = input('Write your next task or leave empty to exit\n> ')
- if not next_task.strip():
- print('Exiting...')
- break
+ if not next_task.strip():
+ print('Exiting...')
+ break
- agent.add_new_task(next_task)
- result = await agent.run()
+ agent.add_new_task(next_task)
+ result = await agent.run()
- print(f"Task '{next_task}' was {'successful' if result.is_successful else 'not successful'}")
+ print(f"Task '{next_task}' was {'successful' if result.is_successful else 'not successful'}")
- if not result.is_successful:
- print('Failed to complete the task. Please try again.')
- continue
+ if not result.is_successful:
+ print('Failed to complete the task. Please try again.')
+ continue
- finally:
- # Stop the browser session
- await browser_session.stop()
+ finally:
+ # Stop the browser session
+ await browser_session.stop()
if __name__ == '__main__':