Skip to content

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

lint

PaperBoardOfficialae4a423e3ddf
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 697906596..70caddafe 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -105,10 +105,10 @@ class BrowserContextConfig(BaseModel):
include_dynamic_attributes: bool = True
Include dynamic attributes in the CSS selector. If you want to reuse the css_selectors, it might be better to set this to False.
-
+
http_credentials: None
- Dictionary with HTTP basic authentication credentials for corporate intranets (only supports one set of credentials for all URLs at the moment), e.g.
- {"username": "bill", "password": "pa55w0rd"}
+ Dictionary with HTTP basic authentication credentials for corporate intranets (only supports one set of credentials for all URLs at the moment), e.g.
+ {"username": "bill", "password": "pa55w0rd"}
is_mobile: None
Whether the meta viewport tag is taken into account and touch events are enabled.
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index efe243f09..2ccabe496 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -8,6 +8,7 @@ from typing import Dict, Generic, Optional, Tuple, Type, TypeVar, cast
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.prompts import PromptTemplate
+from playwright.async_api import ElementHandle, Page
# from lmnr.sdk.laminar import Laminar
from pydantic import BaseModel
@@ -35,7 +36,6 @@ from browser_use.controller.views import (
WaitForElementAction,
)
from browser_use.utils import time_execution_sync
-from playwright.async_api import Page, ElementHandle
logger = logging.getLogger(__name__)
@@ -637,52 +637,53 @@ class Controller(Generic[Context]):
async def drag_drop(params: DragDropAction, browser: BrowserContext) -> ActionResult:
"""
Performs a precise drag and drop operation between elements or coordinates.
- """
+ """
+
async def get_drag_elements(
- page: Page,
- source_selector: str,
- target_selector: str,
+ page: Page,
+ source_selector: str,
+ target_selector: str,
) -> Tuple[Optional[ElementHandle], Optional[ElementHandle]]:
"""Get source and target elements with appropriate error handling."""
source_element = None
target_element = None
-
+
try:
# page.locator() auto-detects CSS and XPath
source_locator = page.locator(source_selector)
target_locator = page.locator(target_selector)
-
+
# Check if elements exist
source_count = await source_locator.count()
target_count = await target_locator.count()
-
+
if source_count > 0:
source_element = await source_locator.first.element_handle()
- logger.debug(f"Found source element with selector: {source_selector}")
+ logger.debug(f'Found source element with selector: {source_selector}')
else:
- logger.warning(f"Source element not found: {source_selector}")
-
+ logger.warning(f'Source element not found: {source_selector}')
+
if target_count > 0:
target_element = await target_locator.first.element_handle()
- logger.debug(f"Found target element with selector: {target_selector}")
+ logger.debug(f'Found target element with selector: {target_selector}')
else:
- logger.warning(f"Target element not found: {target_selector}")
-
+ logger.warning(f'Target element not found: {target_selector}')
+
except Exception as e:
- logger.error(f"Error finding elements: {str(e)}")
-
+ logger.error(f'Error finding elements: {str(e)}')
+
return source_element, target_element
async def get_element_coordinates(
source_element: ElementHandle,
target_element: ElementHandle,
source_position: Optional[Position],
- target_position: Optional[Position]
+ target_position: Optional[Position],
) -> Tuple[Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
"""Get coordinates from elements with appropriate error handling."""
source_coords = None
target_coords = None
-
+
try:
# Get source coordinates
if source_position:
@@ -691,10 +692,10 @@ class Controller(Generic[Context]):
source_box = await source_element.bounding_box()
if source_box:
source_coords = (
- int(source_box["x"] + source_box["width"] / 2),
- int(source_box["y"] + source_box["height"] / 2)
+ int(source_box['x'] + source_box['width'] / 2),
+ int(source_box['y'] + source_box['height'] / 2),
)
-
+
# Get target coordinates
if target_position:
target_coords = (target_position.x, target_position.y)
@@ -702,12 +703,12 @@ class Controller(Generic[Context]):
target_box = await target_element.bounding_box()
if target_box:
target_coords = (
- int(target_box["x"] + target_box["width"] / 2),
- int(target_box["y"] + target_box["height"] / 2)
+ int(target_box['x'] + target_box['width'] / 2),
+ int(target_box['y'] + target_box['height'] / 2),
)
except Exception as e:
- logger.error(f"Error getting element coordinates: {str(e)}")
-
+ logger.error(f'Error getting element coordinates: {str(e)}')
+
return source_coords, target_coords
async def execute_drag_operation(
@@ -724,96 +725,96 @@ class Controller(Generic[Context]):
# Try to move to source position
try:
await page.mouse.move(source_x, source_y)
- logger.debug(f"Moved to source position ({source_x}, {source_y})")
+ logger.debug(f'Moved to source position ({source_x}, {source_y})')
except Exception as e:
- logger.error(f"Failed to move to source position: {str(e)}")
- return False, f"Failed to move to source position: {str(e)}"
-
+ logger.error(f'Failed to move to source position: {str(e)}')
+ return False, f'Failed to move to source position: {str(e)}'
+
# Press mouse button down
await page.mouse.down()
-
+
# Move to target position with intermediate steps
for i in range(1, steps + 1):
ratio = i / steps
intermediate_x = int(source_x + (target_x - source_x) * ratio)
intermediate_y = int(source_y + (target_y - source_y) * ratio)
-
+
await page.mouse.move(intermediate_x, intermediate_y)
-
+
if delay_ms > 0:
await asyncio.sleep(delay_ms / 1000)
-
+
# Move to final target position
await page.mouse.move(target_x, target_y)
-
+
# Move again to ensure dragover events are properly triggered
await page.mouse.move(target_x, target_y)
-
+
# Release mouse button
await page.mouse.up()
-
- return True, "Drag operation completed successfully"
-
+
+ return True, 'Drag operation completed successfully'
+
except Exception as e:
- return False, f"Error during drag operation: {str(e)}"
+ return False, f'Error during drag operation: {str(e)}'
+
+ page = await browser.get_current_page()
- page = await browser.get_current_page()
-
try:
# Initialize variables
source_x: Optional[int] = None
source_y: Optional[int] = None
target_x: Optional[int] = None
target_y: Optional[int] = None
-
+
# Normalize parameters
steps = max(1, params.steps or 10)
delay_ms = max(0, params.delay_ms or 5)
-
+
# Case 1: Element selectors provided
if params.element_source and params.element_target:
- logger.debug(f"Using element-based approach with selectors")
-
+ logger.debug('Using element-based approach with selectors')
+
source_element, target_element = await get_drag_elements(
- page,
- params.element_source,
- params.element_target,
+ page,
+ params.element_source,
+ params.element_target,
)
-
+
if not source_element or not target_element:
- error_msg = f"Failed to find {'source' if not source_element else 'target'} element"
+ error_msg = f'Failed to find {"source" if not source_element else "target"} element'
return ActionResult(error=error_msg, include_in_memory=True)
-
+
source_coords, target_coords = await get_element_coordinates(
- source_element,
- target_element,
- params.element_source_offset,
- params.element_target_offset
+ source_element, target_element, params.element_source_offset, params.element_target_offset
)
-
+
if not source_coords or not target_coords:
- error_msg = f"Failed to determine {'source' if not source_coords else 'target'} coordinates"
+ error_msg = f'Failed to determine {"source" if not source_coords else "target"} coordinates'
return ActionResult(error=error_msg, include_in_memory=True)
-
+
source_x, source_y = source_coords
target_x, target_y = target_coords
-
+
# Case 2: Coordinates provided directly
- elif all(coord is not None for coord in [params.coord_source_x, params.coord_source_y, params.coord_target_x, params.coord_target_y]):
- logger.debug(f"Using coordinate-based approach")
+ elif all(
+ coord is not None
+ for coord in [params.coord_source_x, params.coord_source_y, params.coord_target_x, params.coord_target_y]
+ ):
+ logger.debug('Using coordinate-based approach')
source_x = params.coord_source_x
source_y = params.coord_source_y
target_x = params.coord_target_x
target_y = params.coord_target_y
else:
- error_msg = "Must provide either source/target selectors or source/target coordinates"
+ error_msg = 'Must provide either source/target selectors or source/target coordinates'
return ActionResult(error=error_msg, include_in_memory=True)
-
+
# Validate coordinates
if any(coord is None for coord in [source_x, source_y, target_x, target_y]):
- error_msg = "Failed to determine source or target coordinates"
+ error_msg = 'Failed to determine source or target coordinates'
return ActionResult(error=error_msg, include_in_memory=True)
-
+
# Perform the drag operation
success, message = await execute_drag_operation(
page,
@@ -824,26 +825,25 @@ class Controller(Generic[Context]):
steps,
delay_ms,
)
-
+
if not success:
- logger.error(f"Drag operation failed: {message}")
+ logger.error(f'Drag operation failed: {message}')
return ActionResult(error=message, include_in_memory=True)
-
+
# Create descriptive message
if params.element_source and params.element_target:
msg = f"🖱️ Dragged element '{params.element_source}' to '{params.element_target}'"
else:
- msg = f"🖱️ Dragged from ({source_x}, {source_y}) to ({target_x}, {target_y})"
-
+ msg = f'🖱️ Dragged from ({source_x}, {source_y}) to ({target_x}, {target_y})'
+
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
-
+
except Exception as e:
- error_msg = f"Failed to perform drag and drop: {str(e)}"
+ error_msg = f'Failed to perform drag and drop: {str(e)}'
logger.error(error_msg)
return ActionResult(error=error_msg, include_in_memory=True)
-
# Register ---------------------------------------------------------------
def action(self, description: str, **kwargs):
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 43a15959c..e1a4fa49c 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -97,23 +97,29 @@ class NoParamsAction(BaseModel):
# No matter what the user sends, discard it and return empty.
return {}
+
class Position(BaseModel):
- x: int
- y: int
+ x: int
+ y: int
+
class DragDropAction(BaseModel):
- # Element-based approach
- element_source: Optional[str] = Field(None, description="CSS selector or XPath of the element to drag from")
- element_target: Optional[str] = Field(None, description="CSS selector or XPath of the element to drop onto")
- element_source_offset: Optional[Position] = Field(None, description="Precise position within the source element to start drag (in pixels from top-left corner)")
- element_target_offset: Optional[Position] = Field(None, description="Precise position within the target element to drop (in pixels from top-left corner)")
-
- # Coordinate-based approach (used if selectors not provided)
- coord_source_x: Optional[int] = Field(None, description="Absolute X coordinate on page to start drag from (in pixels)")
- coord_source_y: Optional[int] = Field(None, description="Absolute Y coordinate on page to start drag from (in pixels)")
- coord_target_x: Optional[int] = Field(None, description="Absolute X coordinate on page to drop at (in pixels)")
- coord_target_y: Optional[int] = Field(None, description="Absolute Y coordinate on page to drop at (in pixels)")
-
- # Common options
- steps: Optional[int] = Field(10, description="Number of intermediate points for smoother movement (5-20 recommended)")
- delay_ms: Optional[int] = Field(5, description="Delay in milliseconds between steps (0 for fastest, 10-20 for more natural)")
+ # Element-based approach
+ element_source: Optional[str] = Field(None, description='CSS selector or XPath of the element to drag from')
+ element_target: Optional[str] = Field(None, description='CSS selector or XPath of the element to drop onto')
+ element_source_offset: Optional[Position] = Field(
+ None, description='Precise position within the source element to start drag (in pixels from top-left corner)'
+ )
+ element_target_offset: Optional[Position] = Field(
+ None, description='Precise position within the target element to drop (in pixels from top-left corner)'
+ )
+
+ # Coordinate-based approach (used if selectors not provided)
+ coord_source_x: Optional[int] = Field(None, description='Absolute X coordinate on page to start drag from (in pixels)')
+ coord_source_y: Optional[int] = Field(None, description='Absolute Y coordinate on page to start drag from (in pixels)')
+ coord_target_x: Optional[int] = Field(None, description='Absolute X coordinate on page to drop at (in pixels)')
+ coord_target_y: Optional[int] = Field(None, description='Absolute Y coordinate on page to drop at (in pixels)')
+
+ # Common options
+ steps: Optional[int] = Field(10, description='Number of intermediate points for smoother movement (5-20 recommended)')
+ delay_ms: Optional[int] = Field(5, description='Delay in milliseconds between steps (0 for fastest, 10-20 for more natural)')
diff --git a/examples/features/drag_drop.py b/examples/features/drag_drop.py
index 074bbfa88..797664943 100644
--- a/examples/features/drag_drop.py
+++ b/examples/features/drag_drop.py
@@ -7,7 +7,6 @@ from pydantic import SecretStr
from browser_use import Agent
-
load_dotenv()
api_key = os.getenv('GEMINI_API_KEY')
if not api_key: