Skip to content

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

more pyupgrade changes

Nick Sweeting2be4ba4f7078
diff --git a/browser_use/agent/playwright_script_generator.py b/browser_use/agent/playwright_script_generator.py
index 3570972e6..a36cc22e3 100644
--- a/browser_use/agent/playwright_script_generator.py
+++ b/browser_use/agent/playwright_script_generator.py
@@ -1,7 +1,7 @@
import json
import logging
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any
from browser_use.browser.browser import BrowserConfig
from browser_use.browser.context import BrowserContextConfig
@@ -14,10 +14,10 @@ class PlaywrightScriptGenerator:
def __init__(
self,
- history_list: List[Dict[str, Any]],
- sensitive_data_keys: Optional[List[str]] = None,
- browser_config: Optional[BrowserConfig] = None,
- context_config: Optional[BrowserContextConfig] = None,
+ history_list: list[dict[str, Any]],
+ sensitive_data_keys: list[str] | None = None,
+ browser_config: BrowserConfig | None = None,
+ context_config: BrowserContextConfig | None = None,
):
"""
Initializes the script generator.
@@ -126,7 +126,7 @@ class PlaywrightScriptGenerator:
options_str = ', '.join(f'{key}={repr(value)}' for key, value in options_dict.items())
return options_str
- def _get_imports_and_helpers(self) -> List[str]:
+ def _get_imports_and_helpers(self) -> list[str]:
"""Generates necessary import statements (excluding helper functions)."""
# Return only the standard imports needed by the main script body
return [
@@ -145,7 +145,7 @@ class PlaywrightScriptGenerator:
# Helper function definitions are no longer here
]
- def _get_sensitive_data_definitions(self) -> List[str]:
+ def _get_sensitive_data_definitions(self) -> list[str]:
"""Generates the SENSITIVE_DATA dictionary definition."""
if not self.sensitive_data_keys:
return ['SENSITIVE_DATA = {}', '']
@@ -160,7 +160,7 @@ class PlaywrightScriptGenerator:
lines.append('')
return lines
- def _get_selector_for_action(self, history_item: dict, action_index_in_step: int) -> Optional[str]:
+ def _get_selector_for_action(self, history_item: dict, action_index_in_step: int) -> str | None:
"""
Gets the selector (preferring XPath) for a given action index within a history step.
Formats the XPath correctly for Playwright.
@@ -207,7 +207,7 @@ class PlaywrightScriptGenerator:
return default_timeout
# --- Action Mapping Methods ---
- def _map_go_to_url(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_go_to_url(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
url = params.get('url')
goto_timeout = self._get_goto_timeout()
script_lines = []
@@ -221,7 +221,7 @@ class PlaywrightScriptGenerator:
script_lines.append(f' # Skipping go_to_url ({step_info_str}): missing or invalid url')
return script_lines
- def _map_wait(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_wait(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
seconds = params.get('seconds', 3)
try:
wait_seconds = int(seconds)
@@ -234,7 +234,7 @@ class PlaywrightScriptGenerator:
def _map_input_text(
self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, **kwargs
- ) -> List[str]:
+ ) -> list[str]:
index = params.get('index')
text = params.get('text', '')
selector = self._get_selector_for_action(history_item, action_index_in_step)
@@ -254,7 +254,7 @@ class PlaywrightScriptGenerator:
def _map_click_element(
self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, action_type: str, **kwargs
- ) -> List[str]:
+ ) -> list[str]:
if action_type == 'click_element_by_index':
logger.warning(f"Mapping legacy 'click_element_by_index' to 'click_element' ({step_info_str})")
index = params.get('index')
@@ -272,7 +272,7 @@ class PlaywrightScriptGenerator:
)
return script_lines
- def _map_scroll_down(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_scroll_down(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
amount = params.get('amount')
script_lines = []
if amount and isinstance(amount, int):
@@ -284,7 +284,7 @@ class PlaywrightScriptGenerator:
script_lines.append(' await page.wait_for_timeout(500)')
return script_lines
- def _map_scroll_up(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_scroll_up(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
amount = params.get('amount')
script_lines = []
if amount and isinstance(amount, int):
@@ -296,7 +296,7 @@ class PlaywrightScriptGenerator:
script_lines.append(' await page.wait_for_timeout(500)')
return script_lines
- def _map_send_keys(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_send_keys(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
keys = params.get('keys')
script_lines = []
if keys and isinstance(keys, str):
@@ -308,7 +308,7 @@ class PlaywrightScriptGenerator:
script_lines.append(f' # Skipping send_keys ({step_info_str}): missing or invalid keys')
return script_lines
- def _map_go_back(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_go_back(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
goto_timeout = self._get_goto_timeout()
return [
' await asyncio.sleep(60) # Wait 1 minute (important) before going back',
@@ -318,7 +318,7 @@ class PlaywrightScriptGenerator:
' await page.wait_for_timeout(1000)',
]
- def _map_open_tab(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_open_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
url = params.get('url')
goto_timeout = self._get_goto_timeout()
script_lines = []
@@ -334,7 +334,7 @@ class PlaywrightScriptGenerator:
script_lines.append(f' # Skipping open_tab ({step_info_str}): missing or invalid url')
return script_lines
- def _map_close_tab(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_close_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
page_id = params.get('page_id')
script_lines = []
if page_id is not None:
@@ -358,7 +358,7 @@ class PlaywrightScriptGenerator:
script_lines.append(f' # Skipping close_tab ({step_info_str}): missing page_id')
return script_lines
- def _map_switch_tab(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_switch_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
page_id = params.get('page_id')
script_lines = []
if page_id is not None:
@@ -378,7 +378,7 @@ class PlaywrightScriptGenerator:
script_lines.append(f' # Skipping switch_tab ({step_info_str}): missing page_id')
return script_lines
- def _map_search_google(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_search_google(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
query = params.get('query')
goto_timeout = self._get_goto_timeout()
script_lines = []
@@ -398,7 +398,7 @@ class PlaywrightScriptGenerator:
script_lines.append(f' # Skipping search_google ({step_info_str}): missing or invalid query')
return script_lines
- def _map_drag_drop(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_drag_drop(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
source_sel = params.get('element_source')
target_sel = params.get('element_target')
source_coords = (params.get('coord_source_x'), params.get('coord_source_y'))
@@ -428,14 +428,14 @@ class PlaywrightScriptGenerator:
script_lines.append(' await page.wait_for_timeout(500)')
return script_lines
- def _map_extract_content(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_extract_content(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
goal = params.get('goal', 'content')
logger.warning(f"Action 'extract_content' ({step_info_str}) cannot be directly translated to Playwright script.")
return [f' # Action: extract_content (Goal: {goal}) - Skipped in Playwright script ({step_info_str})']
def _map_click_download_button(
self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, **kwargs
- ) -> List[str]:
+ ) -> list[str]:
index = params.get('index')
selector = self._get_selector_for_action(history_item, action_index_in_step)
download_dir_in_script = "'./files'" # Default
@@ -481,7 +481,7 @@ class PlaywrightScriptGenerator:
)
return script_lines
- def _map_done(self, params: dict, step_info_str: str, **kwargs) -> List[str]:
+ def _map_done(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
script_lines = []
if isinstance(params, dict):
final_text = params.get('text', '')
@@ -504,10 +504,10 @@ class PlaywrightScriptGenerator:
self,
action_dict: dict,
history_item: dict,
- previous_history_item: Optional[dict],
+ previous_history_item: dict | None,
action_index_in_step: int,
step_info_str: str,
- ) -> List[str]:
+ ) -> list[str]:
"""
Translates a single action dictionary into Playwright script lines using dictionary dispatch.
"""
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index f7782375a..b37c06486 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -1,6 +1,6 @@
import importlib.resources
from datetime import datetime
-from typing import TYPE_CHECKING, List, Optional, Union
+from typing import TYPE_CHECKING, Optional
from langchain_core.messages import HumanMessage, SystemMessage
@@ -14,8 +14,8 @@ class SystemPrompt:
self,
action_description: str,
max_actions_per_step: int = 10,
- override_system_message: Optional[str] = None,
- extend_system_message: Optional[str] = None,
+ override_system_message: str | None = None,
+ extend_system_message: str | None = None,
):
self.default_action_description = action_description
self.max_actions_per_step = max_actions_per_step
@@ -63,7 +63,7 @@ class AgentMessagePrompt:
def __init__(
self,
state: 'BrowserState',
- result: Optional[List['ActionResult']] = None,
+ result: list['ActionResult'] | None = None,
include_attributes: list[str] | None = None,
step_info: Optional['AgentStepInfo'] = None,
):
@@ -142,8 +142,8 @@ class PlannerPrompt(SystemPrompt):
self.available_actions = available_actions
def get_system_message(
- self, is_planner_reasoning: bool, extended_planner_system_prompt: Optional[str] = None
- ) -> Union[SystemMessage, HumanMessage]:
+ self, is_planner_reasoning: bool, extended_planner_system_prompt: str | None = None
+ ) -> SystemMessage | HumanMessage:
"""Get the system message for the planner.
Args:
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index f210d91b6..24060a7ce 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -6,8 +6,9 @@ import logging
import os
import re
import time
+from collections.abc import Awaitable, Callable
from pathlib import Path
-from typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, TypeVar, Union
+from typing import Any, Generic, TypeVar
from dotenv import load_dotenv
from langchain_core.language_models.chat_models import BaseChatModel
@@ -101,34 +102,34 @@ class Agent(Generic[Context]):
browser_context: BrowserContext | None = None,
controller: Controller[Context] = Controller(),
# Initial agent run parameters
- sensitive_data: Optional[Dict[str, str]] = None,
- initial_actions: Optional[List[Dict[str, Dict[str, Any]]]] = None,
+ sensitive_data: dict[str, str] | None = None,
+ initial_actions: list[dict[str, dict[str, Any]]] | None = None,
# Cloud Callbacks
- register_new_step_callback: Union[
- Callable[['BrowserState', 'AgentOutput', int], None], # Sync callback
- Callable[['BrowserState', 'AgentOutput', int], Awaitable[None]], # Async callback
- None,
- ] = None,
- register_done_callback: Union[
- Callable[['AgentHistoryList'], Awaitable[None]], # Async Callback
- Callable[['AgentHistoryList'], None], # Sync Callback
- None,
- ] = None,
+ register_new_step_callback: (
+ Callable[['BrowserState', 'AgentOutput', int], None] # Sync callback
+ | Callable[['BrowserState', 'AgentOutput', int], Awaitable[None]] # Async callback
+ | None
+ ) = None,
+ register_done_callback: (
+ Callable[['AgentHistoryList'], Awaitable[None]] # Async Callback
+ | Callable[['AgentHistoryList'], None] # Sync Callback
+ | None
+ ) = None,
register_external_agent_status_raise_error_callback: Callable[[], Awaitable[bool]] | None = None,
# Agent settings
use_vision: bool = True,
use_vision_for_planner: bool = False,
- save_conversation_path: Optional[str] = None,
- save_conversation_path_encoding: Optional[str] = 'utf-8',
+ save_conversation_path: str | None = None,
+ save_conversation_path_encoding: str | None = 'utf-8',
max_failures: int = 3,
retry_delay: int = 10,
- override_system_message: Optional[str] = None,
- extend_system_message: Optional[str] = None,
+ override_system_message: str | None = None,
+ extend_system_message: str | None = None,
max_input_tokens: int = 128000,
validate_output: bool = False,
- message_context: Optional[str] = None,
+ message_context: str | None = None,
generate_gif: bool | str = False,
- available_file_paths: Optional[list[str]] = None,
+ available_file_paths: list[str] | None = None,
include_attributes: list[str] = [
'title',
'type',
@@ -142,18 +143,18 @@ class Agent(Generic[Context]):
'data-date-format',
],
max_actions_per_step: int = 10,
- tool_calling_method: Optional[ToolCallingMethod] = 'auto',
- page_extraction_llm: Optional[BaseChatModel] = None,
- planner_llm: Optional[BaseChatModel] = None,
+ tool_calling_method: ToolCallingMethod | None = 'auto',
+ page_extraction_llm: BaseChatModel | None = None,
+ planner_llm: BaseChatModel | None = None,
planner_interval: int = 1, # Run planner every N steps
is_planner_reasoning: bool = False,
- extend_planner_system_message: Optional[str] = None,
- injected_agent_state: Optional[AgentState] = None,
+ extend_planner_system_message: str | None = None,
+ injected_agent_state: AgentState | None = None,
context: Context | None = None,
- save_playwright_script_path: Optional[str] = None,
+ save_playwright_script_path: str | None = None,
enable_memory: bool = True,
- memory_config: Optional[MemoryConfig] = None,
- source: Optional[str] = None,
+ memory_config: MemoryConfig | None = None,
+ source: str | None = None,
):
if page_extraction_llm is None:
page_extraction_llm = llm
@@ -312,7 +313,7 @@ class Agent(Generic[Context]):
self.settings.message_context = f'Available actions: {self.unfiltered_actions}'
return self.settings.message_context
- def _set_browser_use_version_and_source(self, source_override: Optional[str] = None) -> None:
+ def _set_browser_use_version_and_source(self, source_override: str | None = None) -> None:
"""Get the version and source of the browser-use package (git or pip in a nutshell)"""
try:
# First check for repository-specific files
@@ -374,7 +375,7 @@ class Agent(Generic[Context]):
self.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'])
self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)
- def _set_tool_calling_method(self) -> Optional[ToolCallingMethod]:
+ def _set_tool_calling_method(self) -> ToolCallingMethod | None:
tool_calling_method = self.settings.tool_calling_method
if tool_calling_method == 'auto':
if is_model_without_tool_support(self.model_name):
@@ -406,7 +407,7 @@ class Agent(Generic[Context]):
# @observe(name='agent.step', ignore_output=True, ignore_input=True)
@time_execution_async('--step (agent)')
- async def step(self, step_info: Optional[AgentStepInfo] = None) -> None:
+ async def step(self, step_info: AgentStepInfo | None = None) -> None:
"""Execute one step of the task"""
logger.info(f'📍 Step {self.state.n_steps}')
state = None
@@ -634,7 +635,7 @@ class Agent(Generic[Context]):
model_output: AgentOutput | None,
state: BrowserState,
result: list[ActionResult],
- metadata: Optional[StepMetadata] = None,
+ metadata: StepMetadata | None = None,
) -> None:
"""Create and store history item"""
@@ -1149,10 +1150,10 @@ class Agent(Generic[Context]):
async def _update_action_indices(
self,
- historical_element: Optional[DOMHistoryElement],
+ historical_element: DOMHistoryElement | None,
action: ActionModel, # Type this properly based on your action model
current_state: BrowserState,
- ) -> Optional[ActionModel]:
+ ) -> ActionModel | None:
"""
Update action indices based on current page state.
Returns updated action or None if element cannot be found.
@@ -1172,7 +1173,7 @@ class Agent(Generic[Context]):
return action
- async def load_and_rerun(self, history_file: Optional[str | Path] = None, **kwargs) -> list[ActionResult]:
+ async def load_and_rerun(self, history_file: str | Path | None = None, **kwargs) -> list[ActionResult]:
"""
Load history from file and rerun it.
@@ -1185,7 +1186,7 @@ class Agent(Generic[Context]):
history = AgentHistoryList.load_from_file(history_file, self.AgentOutput)
return await self.rerun_history(history, **kwargs)
- def save_history(self, file_path: Optional[str | Path] = None) -> None:
+ def save_history(self, file_path: str | Path | None = None) -> None:
"""Save the history to a file"""
if not file_path:
file_path = 'AgentHistory.json'
@@ -1221,7 +1222,7 @@ class Agent(Generic[Context]):
logger.info('⏹️ Agent stopping')
self.state.stopped = True
- def _convert_initial_actions(self, actions: List[Dict[str, Dict[str, Any]]]) -> List[ActionModel]:
+ def _convert_initial_actions(self, actions: list[dict[str, dict[str, Any]]]) -> list[ActionModel]:
"""Convert dictionary-based actions to ActionModel instances"""
converted_actions = []
action_model = self.ActionModel
@@ -1294,7 +1295,7 @@ class Agent(Generic[Context]):
else:
pass
- async def _run_planner(self) -> Optional[str]:
+ async def _run_planner(self) -> str | None:
"""Run the planner to analyze state and suggest next steps"""
# Skip planning if no planner_llm is set
if not self.settings.planner_llm:
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 628821bd1..a073327f3 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -12,7 +12,7 @@ import re
import time
import uuid
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import anyio
from patchright._impl._errors import TimeoutError
@@ -173,7 +173,7 @@ class BrowserContextConfig(BaseModel):
browser_window_size: BrowserContextWindowSize = Field(
default_factory=lambda: BrowserContextWindowSize(width=1280, height=1100)
)
- no_viewport: Optional[bool] = None
+ no_viewport: bool | None = None
save_recording_path: str | None = None
save_downloads_path: str | None = None
@@ -277,7 +277,7 @@ class BrowserContext:
self,
browser: 'Browser',
config: BrowserContextConfig | None = None,
- state: Optional[BrowserContextState] = None,
+ state: BrowserContextState | None = None,
):
self.context_id = str(uuid.uuid4())
@@ -1256,7 +1256,7 @@ class BrowserContext:
return f"{tag_name}[highlight_index='{element.highlight_index}']"
@time_execution_async('--get_locate_element')
- async def get_locate_element(self, element: DOMElementNode) -> Optional[ElementHandle]:
+ async def get_locate_element(self, element: DOMElementNode) -> ElementHandle | None:
current_frame = await self.get_current_page()
# Start with the target element and collect all parents
@@ -1301,7 +1301,7 @@ class BrowserContext:
return None
@time_execution_async('--get_locate_element_by_xpath')
- async def get_locate_element_by_xpath(self, xpath: str) -> Optional[ElementHandle]:
+ async def get_locate_element_by_xpath(self, xpath: str) -> ElementHandle | None:
"""
Locates an element on the page using the provided XPath.
"""
@@ -1321,7 +1321,7 @@ class BrowserContext:
return None
@time_execution_async('--get_locate_element_by_css_selector')
- async def get_locate_element_by_css_selector(self, css_selector: str) -> Optional[ElementHandle]:
+ async def get_locate_element_by_css_selector(self, css_selector: str) -> ElementHandle | None:
"""
Locates an element on the page using the provided CSS selector.
"""
@@ -1342,8 +1342,8 @@ class BrowserContext:
@time_execution_async('--get_locate_element_by_text')
async def get_locate_element_by_text(
- self, text: str, nth: Optional[int] = 0, element_type: Optional[str] = None
- ) -> Optional[ElementHandle]:
+ self, text: str, nth: int | None = 0, element_type: str | None = None
+ ) -> ElementHandle | None:
"""
Locates an element on the page using the provided text.
If `nth` is provided, it returns the nth matching element (0-based).
@@ -1424,7 +1424,7 @@ class BrowserContext:
raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')
@time_execution_async('--click_element_node')
- async def _click_element_node(self, element_node: DOMElementNode) -> Optional[str]:
+ async def _click_element_node(self, element_node: DOMElementNode) -> str | None:
"""
Optimized method to click an element using xpath.
"""
@@ -1493,7 +1493,7 @@ class BrowserContext:
for page_id, page in enumerate(session.context.pages):
try:
tab_info = TabInfo(page_id=page_id, url=page.url, title=await asyncio.wait_for(page.title(), timeout=1))
- except asyncio.TimeoutError:
+ except TimeoutError:
# page.title() can hang forever on tabs that are crashed/disappeared/about:blank
# we dont want to try automating those tabs because they will hang the whole script
logger.debug('⚠ Failed to get tab info for tab #%s: %s (ignoring)', page_id, page.url)
diff --git a/browser_use/browser/dolphin_service.py b/browser_use/browser/dolphin_service.py
index 82972d224..cb4d13272 100644
--- a/browser_use/browser/dolphin_service.py
+++ b/browser_use/browser/dolphin_service.py
@@ -1,6 +1,5 @@
import logging
import os
-from typing import List, Optional
import aiohttp
from patchright.async_api import Page, async_playwright
@@ -34,7 +33,7 @@ class DolphinBrowser(Browser):
self.page = None
self.headless = headless
self.keep_open = keep_open
- self._pages: List[Page] = [] # List to store open pages
+ self._pages: list[Page] = [] # List to store open pages
self.session = None
self.cached_state = None
@@ -185,7 +184,7 @@ class DolphinBrowser(Browser):
data = await response.json()
return data.get('data', []) # Return the profiles array from the response
- async def start_profile(self, profile_id: Optional[str] = None, headless: bool = False) -> dict:
+ async def start_profile(self, profile_id: str | None = None, headless: bool = False) -> dict:
"""
Start a browser profile on Dolphin Anty.
@@ -218,7 +217,7 @@ class DolphinBrowser(Browser):
raise Exception(f'Failed to start profile: {await response.text()}')
return await response.json()
- async def stop_profile(self, profile_id: Optional[str] = None):
+ async def stop_profile(self, profile_id: str | None = None):
"""
Stop a browser profile on Dolphin Anty.
@@ -243,7 +242,7 @@ class DolphinBrowser(Browser):
async with session.get(url) as response:
return await response.json()
- async def connect(self, profile_id: Optional[str] = None):
+ async def connect(self, profile_id: str | None = None):
"""
Connect to a running browser profile using Playwright.
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index 73304bc42..c41e91227 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import Any, Optional
+from typing import Any
from pydantic import BaseModel
@@ -14,13 +14,13 @@ class TabInfo(BaseModel):
page_id: int
url: str
title: str
- parent_page_id: Optional[int] = None # parent page that contains this popup or cross-origin iframe
+ parent_page_id: int | None = None # parent page that contains this popup or cross-origin iframe
class GroupTabsAction(BaseModel):
tab_ids: list[int]
title: str
- color: Optional[str] = 'blue'
+ color: str | None = 'blue'
class UngroupTabsAction(BaseModel):
@@ -32,7 +32,7 @@ class BrowserState(DOMState):
url: str
title: str
tabs: list[TabInfo]
- screenshot: Optional[str] = None
+ screenshot: str | None = None
pixels_above: int = 0
pixels_below: int = 0
browser_errors: list[str] = field(default_factory=list)
@@ -44,7 +44,7 @@ class BrowserStateHistory:
title: str
tabs: list[TabInfo]
interacted_element: list[DOMHistoryElement | None] | list[None]
- screenshot: Optional[str] = None
+ screenshot: str | None = None
def to_dict(self) -> dict[str, Any]:
data = {}
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index d6aad0194..4311f7004 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -1,6 +1,7 @@
import asyncio
+from collections.abc import Callable
from inspect import iscoroutinefunction, signature
-from typing import Any, Callable, Dict, Generic, Optional, Type, TypeVar
+from typing import Any, Generic, Optional, TypeVar
from langchain_core.language_models.chat_models import BaseChatModel
from pydantic import BaseModel, Field, create_model
@@ -30,7 +31,7 @@ class Registry(Generic[Context]):
self.exclude_actions = exclude_actions if exclude_actions is not None else []
# @time_execution_sync('--create_param_model')
- def _create_param_model(self, function: Callable) -> Type[BaseModel]:
+ def _create_param_model(self, function: Callable) -> type[BaseModel]:
"""Creates a Pydantic model from function signature"""
sig = signature(function)
params = {
@@ -48,9 +49,9 @@ class Registry(Generic[Context]):
def action(
self,
description: str,
- param_model: Optional[Type[BaseModel]] = None,
- domains: Optional[list[str]] = None,
- page_filter: Optional[Callable[[Any], bool]] = None,
+ param_model: type[BaseModel] | None = None,
+ domains: list[str] | None = None,
+ page_filter: Callable[[Any], bool] | None = None,
):
"""Decorator for registering actions"""
@@ -94,10 +95,10 @@ class Registry(Generic[Context]):
self,
action_name: str,
params: dict,
- browser: Optional[BrowserContext] = None,
- page_extraction_llm: Optional[BaseChatModel] = None,
- sensitive_data: Optional[Dict[str, str]] = None,
- available_file_paths: Optional[list[str]] = None,
+ browser: BrowserContext | None = None,
+ page_extraction_llm: BaseChatModel | None = None,
+ sensitive_data: dict[str, str] | None = None,
+ available_file_paths: list[str] | None = None,
#
context: Context | None = None,
) -> Any:
@@ -149,7 +150,7 @@ class Registry(Generic[Context]):
except Exception as e:
raise RuntimeError(f'Error executing action {action_name}: {str(e)}') from e
- def _replace_sensitive_data(self, params: BaseModel, sensitive_data: Dict[str, str]) -> BaseModel:
+ def _replace_sensitive_data(self, params: BaseModel, sensitive_data: dict[str, str]) -> BaseModel:
"""Replaces the sensitive data in the params"""
# if there are any str with <secret>placeholder</secret> in the params, replace them with the actual value from sensitive_data
@@ -175,7 +176,7 @@ class Registry(Generic[Context]):
return type(params).model_validate(processed_params)
# @time_execution_sync('--create_action_model')
- def create_action_model(self, include_actions: Optional[list[str]] = None, page=None) -> Type[ActionModel]:
+ def create_action_model(self, include_actions: list[str] | None = None, page=None) -> type[ActionModel]:
"""Creates a Pydantic model from registered actions, used by LLM APIs that support tool calling & enforce a schema"""
# Filter actions based on page if provided:
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index a1e3e9eb6..46e0b8e77 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -1,4 +1,4 @@
-from typing import Callable, Dict, Type
+from collections.abc import Callable
from patchright.async_api import Page
from pydantic import BaseModel, ConfigDict
@@ -10,7 +10,7 @@ class RegisteredAction(BaseModel):
name: str
description: str
function: Callable
- param_model: Type[BaseModel]
+ param_model: type[BaseModel]
# filters: provide specific domains or a function to determine whether the action should be available on the given page or not
domains: list[str] | None = None # e.g. ['*.google.com', 'www.bing.com', 'yahoo.*]
@@ -68,7 +68,7 @@ class ActionModel(BaseModel):
class ActionRegistry(BaseModel):
"""Model representing the action registry"""
- actions: Dict[str, RegisteredAction] = {}
+ actions: dict[str, RegisteredAction] = {}
@staticmethod
def _match_domains(domains: list[str] | None, url: str) -> bool:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 4d6873265..75f5a72a9 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -3,7 +3,7 @@ import enum
import json
import logging
import re
-from typing import Dict, Generic, Optional, Tuple, Type, TypeVar, cast
+from typing import Generic, TypeVar, cast
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.prompts import PromptTemplate
@@ -42,7 +42,7 @@ class Controller(Generic[Context]):
def __init__(
self,
exclude_actions: list[str] = [],
- output_model: Optional[Type[BaseModel]] = None,
+ output_model: type[BaseModel] | None = None,
):
self.registry = Registry[Context](exclude_actions)
@@ -527,7 +527,7 @@ class Controller(Generic[Context]):
page: Page,
source_selector: str,
target_selector: str,
- ) -> Tuple[Optional[ElementHandle], Optional[ElementHandle]]:
+ ) -> tuple[ElementHandle | None, ElementHandle | None]:
"""Get source and target elements with appropriate error handling."""
source_element = None
target_element = None
@@ -561,9 +561,9 @@ class Controller(Generic[Context]):
async def get_element_coordinates(
source_element: ElementHandle,
target_element: ElementHandle,
- source_position: Optional[Position],
- target_position: Optional[Position],
- ) -> Tuple[Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
+ source_position: Position | None,
+ target_position: Position | None,
+ ) -> tuple[tuple[int, int] | None, tuple[int, int] | None]:
"""Get coordinates from elements with appropriate error handling."""
source_coords = None
target_coords = None
@@ -603,7 +603,7 @@ class Controller(Generic[Context]):
target_y: int,
steps: int,
delay_ms: int,
- ) -> Tuple[bool, str]:
+ ) -> tuple[bool, str]:
"""Execute the drag operation with comprehensive error handling."""
try:
# Try to move to source position
@@ -646,10 +646,10 @@ class Controller(Generic[Context]):
try:
# Initialize variables
- source_x: Optional[int] = None
- source_y: Optional[int] = None
- target_x: Optional[int] = None
- target_y: Optional[int] = None
+ source_x: int | None = None
+ source_y: int | None = None
+ target_x: int | None = None
+ target_y: int | None = None
# Normalize parameters
steps = max(1, params.steps or 10)
@@ -745,9 +745,9 @@ class Controller(Generic[Context]):
action: ActionModel,
browser_context: BrowserContext,
#
- page_extraction_llm: Optional[BaseChatModel] = None,
- sensitive_data: Optional[Dict[str, str]] = None,
- available_file_paths: Optional[list[str]] = None,
+ page_extraction_llm: BaseChatModel | None = None,
+ sensitive_data: dict[str, str] | None = None,
+ available_file_paths: list[str] | None = None,
#
context: Context | None = None,
) -> ActionResult:
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 04ffb9758..166989d09 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from pydantic import BaseModel, ConfigDict, Field, model_validator
@@ -14,13 +12,13 @@ class GoToUrlAction(BaseModel):
class ClickElementAction(BaseModel):
index: int
- xpath: Optional[str] = None
+ xpath: str | None = None
class InputTextAction(BaseModel):
index: int
text: str
- xpath: Optional[str] = None
+ xpath: str | None = None
class DoneAction(BaseModel):
@@ -41,7 +39,7 @@ class CloseTabAction(BaseModel):
class ScrollAction(BaseModel):
- amount: Optional[int] = None # The number of pixels to scroll. If None, scroll down/up one page
+ amount: int | None = None # The number of pixels to scroll. If None, scroll down/up one page
class SendKeysAction(BaseModel):
@@ -51,7 +49,7 @@ class SendKeysAction(BaseModel):
class GroupTabsAction(BaseModel):
tab_ids: list[int] = Field(..., description='List of tab IDs to group')
title: str = Field(..., description='Name for the tab group')
- color: Optional[str] = Field(
+ color: str | None = Field(
'blue',
description='Color for the group (grey/blue/red/yellow/green/pink/purple/cyan)',
)
@@ -86,21 +84,21 @@ class Position(BaseModel):
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(
+ element_source: str | None = Field(None, description='CSS selector or XPath of the element to drag from')
+ element_target: str | None = Field(None, description='CSS selector or XPath of the element to drop onto')
+ element_source_offset: Position | None = Field(
None, description='Precise position within the source element to start drag (in pixels from top-left corner)'
)
- element_target_offset: Optional[Position] = Field(
+ element_target_offset: Position | None = 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)')
+ coord_source_x: int | None = Field(None, description='Absolute X coordinate on page to start drag from (in pixels)')
+ coord_source_y: int | None = Field(None, description='Absolute Y coordinate on page to start drag from (in pixels)')
+ coord_target_x: int | None = Field(None, description='Absolute X coordinate on page to drop at (in pixels)')
+ coord_target_y: int | None = 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)')
+ steps: int | None = Field(10, description='Number of intermediate points for smoother movement (5-20 recommended)')
+ delay_ms: int | None = Field(5, description='Delay in milliseconds between steps (0 for fastest, 10-20 for more natural)')
diff --git a/browser_use/dom/history_tree_processor/service.py b/browser_use/dom/history_tree_processor/service.py
index fee43125c..816b2fdd0 100644
--- a/browser_use/dom/history_tree_processor/service.py
+++ b/browser_use/dom/history_tree_processor/service.py
@@ -1,5 +1,4 @@
import hashlib
-from typing import Optional
from browser_use.dom.history_tree_processor.view import DOMHistoryElement, HashedDomElement
from browser_use.dom.views import DOMElementNode
@@ -32,7 +31,7 @@ class HistoryTreeProcessor:
)
@staticmethod
- def find_history_element_in_tree(dom_history_element: DOMHistoryElement, tree: DOMElementNode) -> Optional[DOMElementNode]:
+ def find_history_element_in_tree(dom_history_element: DOMHistoryElement, tree: DOMElementNode) -> DOMElementNode | None:
hashed_dom_history_element = HistoryTreeProcessor._hash_dom_history_element(dom_history_element)
def process_node(node: DOMElementNode):
diff --git a/browser_use/dom/history_tree_processor/view.py b/browser_use/dom/history_tree_processor/view.py
index 250a64903..2984d4ae9 100644
--- a/browser_use/dom/history_tree_processor/view.py
+++ b/browser_use/dom/history_tree_processor/view.py
@@ -1,5 +1,4 @@
from dataclasses import dataclass
-from typing import Optional
from pydantic import BaseModel
@@ -42,14 +41,14 @@ class ViewportInfo(BaseModel):
class DOMHistoryElement:
tag_name: str
xpath: str
- highlight_index: Optional[int]
+ highlight_index: int | None
entire_parent_branch_path: list[str]
attributes: dict[str, str]
shadow_root: bool = False
- css_selector: Optional[str] = None
- page_coordinates: Optional[CoordinateSet] = None
- viewport_coordinates: Optional[CoordinateSet] = None
- viewport_info: Optional[ViewportInfo] = None
+ css_selector: str | None = None
+ page_coordinates: CoordinateSet | None = None
+ viewport_coordinates: CoordinateSet | None = None
+ viewport_info: ViewportInfo | None = None
def to_dict(self) -> dict:
page_coordinates = self.page_coordinates.model_dump() if self.page_coordinates else None
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index d61e76cc3..c2d71874e 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -2,7 +2,7 @@ import json
import logging
from dataclasses import dataclass
from importlib import resources
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from urllib.parse import urlparse
if TYPE_CHECKING:
@@ -160,7 +160,7 @@ class DomService:
def _parse_node(
self,
node_data: dict,
- ) -> tuple[Optional[DOMBaseNode], list[int]]:
+ ) -> tuple[DOMBaseNode | None, list[int]]:
if not node_data:
return None, []
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index bac702de3..0a7076b54 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from functools import cached_property
-from typing import TYPE_CHECKING, Dict, List, Optional
+from typing import TYPE_CHECKING, Optional
from browser_use.dom.history_tree_processor.view import CoordinateSet, HashedDomElement, ViewportInfo
from browser_use.utils import time_execution_sync
@@ -61,23 +61,23 @@ class DOMElementNode(DOMBaseNode):
tag_name: str
xpath: str
- attributes: Dict[str, str]
- children: List[DOMBaseNode]
+ attributes: dict[str, str]
+ children: list[DOMBaseNode]
is_interactive: bool = False
is_top_element: bool = False
is_in_viewport: bool = False
shadow_root: bool = False
- highlight_index: Optional[int] = None
- viewport_coordinates: Optional[CoordinateSet] = None
- page_coordinates: Optional[CoordinateSet] = None
- viewport_info: Optional[ViewportInfo] = None
+ highlight_index: int | None = None
+ viewport_coordinates: CoordinateSet | None = None
+ page_coordinates: CoordinateSet | None = None
+ viewport_info: ViewportInfo | None = None
"""
### State injected by the browser context.
The idea is that the clickable elements are sometimes persistent from the previous page -> tells the model which objects are new/_how_ the state has changed
"""
- is_new: Optional[bool] = None
+ is_new: bool | None = None
def __json__(self) -> dict:
return {
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index 887fe7e7f..9fe8cdfe3 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -36,11 +36,11 @@ def addLoggingLevel(levelName, levelNum, methodName=None):
methodName = levelName.lower()
if hasattr(logging, levelName):
- raise AttributeError('{} already defined in logging module'.format(levelName))
+ raise AttributeError(f'{levelName} already defined in logging module')
if hasattr(logging, methodName):
- raise AttributeError('{} already defined in logging module'.format(methodName))
+ raise AttributeError(f'{methodName} already defined in logging module')
if hasattr(logging.getLoggerClass(), methodName):
- raise AttributeError('{} already defined in logger class'.format(methodName))
+ raise AttributeError(f'{methodName} already defined in logger class')
# This method was inspired by the answers to Stack Overflow post
# http://stackoverflow.com/q/2183233/2988730, especially
diff --git a/browser_use/telemetry/views.py b/browser_use/telemetry/views.py
index fdba27303..975e0e645 100644
--- a/browser_use/telemetry/views.py
+++ b/browser_use/telemetry/views.py
@@ -1,6 +1,7 @@
from abc import ABC, abstractmethod
+from collections.abc import Sequence
from dataclasses import asdict, dataclass
-from typing import Any, Dict, Sequence
+from typing import Any
@dataclass
@@ -11,7 +12,7 @@ class BaseTelemetryEvent(ABC):
pass
@property
- def properties(self) -> Dict[str, Any]:
+ def properties(self) -> dict[str, Any]:
return {k: v for k, v in asdict(self).items() if k != 'name'}
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 95ea0ee51..a423da308 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -4,9 +4,10 @@ import os
import platform
import signal
import time
+from collections.abc import Callable, Coroutine
from functools import wraps
from sys import stderr
-from typing import Any, Callable, Coroutine, List, Optional, ParamSpec, TypeVar
+from typing import Any, ParamSpec, TypeVar
logger = logging.getLogger(__name__)
@@ -33,12 +34,12 @@ class SignalHandler:
def __init__(
self,
- loop: Optional[asyncio.AbstractEventLoop] = None,
- pause_callback: Optional[Callable[[], None]] = None,
- resume_callback: Optional[Callable[[], None]] = None,
- custom_exit_callback: Optional[Callable[[], None]] = None,
+ loop: asyncio.AbstractEventLoop | None = None,
+ pause_callback: Callable[[], None] | None = None,
+ resume_callback: Callable[[], None] | None = None,
+ custom_exit_callback: Callable[[], None] | None = None,
exit_on_second_int: bool = True,
- interruptible_task_patterns: List[str] = None,
+ interruptible_task_patterns: list[str] = None,
):
"""
Initialize the signal handler.
diff --git a/eval/service.py b/eval/service.py
index 207ad846e..f1f68eba9 100644
--- a/eval/service.py
+++ b/eval/service.py
@@ -290,7 +290,6 @@ import subprocess
import time
from datetime import datetime
from pathlib import Path
-from typing import Dict, Optional
import requests
from dotenv import load_dotenv
@@ -566,7 +565,7 @@ async def run_agent_with_tracing(
await agent.close() # This will close the browser if we created it
-async def judge_task_result(model, task_folder: Path, score_threshold: float = 3) -> Dict:
+async def judge_task_result(model, task_folder: Path, score_threshold: float = 3) -> dict:
"""
Judge a single task result based on the success value of the final action.
@@ -640,7 +639,7 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3
}
-def calculate_local_summary(results_dir: Optional[str] = None) -> Dict:
+def calculate_local_summary(results_dir: str | None = None) -> dict:
"""
Calculates a summary of task results by reading the saved result.json files.
Does not make any network requests.
@@ -954,11 +953,11 @@ async def run_multiple_tasks(
max_parallel_evaluations: int = 5,
max_steps_per_task: int = 25,
start_index: int = 0,
- end_index: Optional[int] = None,
+ end_index: int | None = None,
headless: bool = False,
use_vision: bool = True,
fresh_start: bool = True,
-) -> Dict:
+) -> dict:
"""
Run multiple tasks in parallel and evaluate results.
"""
diff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.py
index 42bd4ed6d..e5ac190cc 100644
--- a/examples/custom-functions/hover_element.py
+++ b/examples/custom-functions/hover_element.py
@@ -1,6 +1,5 @@
import os
import sys
-from typing import Optional
from pydantic import BaseModel
@@ -17,9 +16,9 @@ from browser_use.browser.context import BrowserContext
class HoverAction(BaseModel):
- index: Optional[int] = None
- xpath: Optional[str] = None
- selector: Optional[str] = None
+ index: int | None = None
+ xpath: str | None = None
+ selector: str | None = None
browser = Browser(
diff --git a/examples/custom-functions/save_to_file_hugging_face.py b/examples/custom-functions/save_to_file_hugging_face.py
index 96434b05c..9c2f1e86e 100644
--- a/examples/custom-functions/save_to_file_hugging_face.py
+++ b/examples/custom-functions/save_to_file_hugging_face.py
@@ -4,7 +4,6 @@ import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import asyncio
-from typing import List
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
@@ -24,7 +23,7 @@ class Model(BaseModel):
class Models(BaseModel):
- models: List[Model]
+ models: list[Model]
@controller.action('Save models', param_model=Models)
diff --git a/examples/features/custom_output.py b/examples/features/custom_output.py
index a406d5a63..285a188f8 100644
--- a/examples/features/custom_output.py
+++ b/examples/features/custom_output.py
@@ -6,7 +6,6 @@ Show how to use custom outputs.
import os
import sys
-from typing import List
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -29,7 +28,7 @@ class Post(BaseModel):
class Posts(BaseModel):
- posts: List[Post]
+ posts: list[Post]
controller = Controller(output_model=Posts)
diff --git a/examples/features/task_with_memory.py b/examples/features/task_with_memory.py
index 3e35b343c..b2035be6a 100644
--- a/examples/features/task_with_memory.py
+++ b/examples/features/task_with_memory.py
@@ -1,6 +1,5 @@
import asyncio
import json
-from typing import List
import anyio
from dotenv import load_dotenv
@@ -48,7 +47,7 @@ class Link(BaseModel):
class Links(BaseModel):
- links: List[Link]
+ links: list[Link]
initial_actions = [
diff --git a/examples/ui/gradio_demo.py b/examples/ui/gradio_demo.py
index aa3915eb3..6cc88deef 100644
--- a/examples/ui/gradio_demo.py
+++ b/examples/ui/gradio_demo.py
@@ -1,7 +1,6 @@
import asyncio
import os
from dataclasses import dataclass
-from typing import List, Optional
# Third-party imports
import gradio as gr
@@ -20,15 +19,15 @@ load_dotenv()
@dataclass
class ActionResult:
is_done: bool
- extracted_content: Optional[str]
- error: Optional[str]
+ extracted_content: str | None
+ error: str | None
include_in_memory: bool
@dataclass
class AgentHistoryList:
- all_results: List[ActionResult]
- all_model_outputs: List[dict]
+ all_results: list[ActionResult]
+ all_model_outputs: list[dict]
def parse_agent_history(history_str: str) -> None:
diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.py
index 6e2fd96f2..4cfcc90ba 100644
--- a/examples/use-cases/find_and_apply_to_jobs.py
+++ b/examples/use-cases/find_and_apply_to_jobs.py
@@ -11,7 +11,6 @@ import logging
import os
import sys
from pathlib import Path
-from typing import Optional
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -47,8 +46,8 @@ class Job(BaseModel):
link: str
company: str
fit_score: float
- location: Optional[str] = None
- salary: Optional[str] = None
+ location: str | None = None
+ salary: str | None = None
@controller.action('Save jobs to file - with a score how well it fits to my profile', param_model=Job)
diff --git a/examples/use-cases/find_influencer_profiles.py b/examples/use-cases/find_influencer_profiles.py
index a0e43e390..581425bcd 100644
--- a/examples/use-cases/find_influencer_profiles.py
+++ b/examples/use-cases/find_influencer_profiles.py
@@ -7,7 +7,6 @@ Show how to use custom outputs.
import json
import os
import sys
-from typing import List
import httpx
@@ -32,7 +31,7 @@ class Profile(BaseModel):
class Profiles(BaseModel):
- profiles: List[Profile]
+ profiles: list[Profile]
controller = Controller(exclude_actions=['search_google'], output_model=Profiles)
diff --git a/tests/test_browser_window_size_height.py b/tests/test_browser_window_size_height.py
index 1c3fa5345..aba22e0b2 100644
--- a/tests/test_browser_window_size_height.py
+++ b/tests/test_browser_window_size_height.py
@@ -5,7 +5,7 @@ This script shows how to set a custom window size for the browser.
import asyncio
import sys
-from typing import Any, Dict
+from typing import Any
from browser_use.browser.browser import Browser, BrowserConfig
from browser_use.browser.context import BrowserContextConfig, BrowserContextWindowSize
@@ -86,7 +86,7 @@ async def main():
await browser.close()
-def validate_window_size(configured: Dict[str, Any], actual: Dict[str, Any]) -> None:
+def validate_window_size(configured: dict[str, Any], actual: dict[str, Any]) -> None:
"""Compare configured window size with actual size and report differences"""
# Allow for small differences due to browser chrome, scrollbars, etc.
width_diff = abs(configured['width'] - actual['width'])
diff --git a/tests/test_controller.py b/tests/test_controller.py
index 61d20c306..7f67effa3 100644
--- a/tests/test_controller.py
+++ b/tests/test_controller.py
@@ -1,6 +1,5 @@
import asyncio
import time
-from typing import Optional
import pytest
from pydantic import BaseModel
@@ -64,7 +63,7 @@ class TestControllerIntegration:
# Create the ActionModel instance
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
action_model = GoToUrlActionModel(**action_data)
@@ -86,7 +85,7 @@ class TestControllerIntegration:
goto_action = {'go_to_url': GoToUrlAction(url='https://google.com')}
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
await controller.act(GoToUrlActionModel(**goto_action), browser_context)
@@ -94,7 +93,7 @@ class TestControllerIntegration:
scroll_action = {'scroll_down': ScrollAction(amount=200)}
class ScrollActionModel(ActionModel):
- scroll_down: Optional[ScrollAction] = None
+ scroll_down: ScrollAction | None = None
# Execute scroll down
result = await controller.act(ScrollActionModel(**scroll_action), browser_context)
@@ -107,7 +106,7 @@ class TestControllerIntegration:
scroll_up_action = {'scroll_up': ScrollAction(amount=100)}
class ScrollUpActionModel(ActionModel):
- scroll_up: Optional[ScrollAction] = None
+ scroll_up: ScrollAction | None = None
# Execute scroll up
result = await controller.act(ScrollUpActionModel(**scroll_up_action), browser_context)
@@ -156,7 +155,7 @@ class TestControllerIntegration:
goto_action = {'go_to_url': GoToUrlAction(url='https://google.com')}
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
await controller.act(GoToUrlActionModel(**goto_action), browser_context)
@@ -164,7 +163,7 @@ class TestControllerIntegration:
custom_action_data = {'custom_action': CustomParams(text='test_value')}
class CustomActionModel(ActionModel):
- custom_action: Optional[CustomParams] = None
+ custom_action: CustomParams | None = None
# Execute the custom action
result = await controller.act(CustomActionModel(**custom_action_data), browser_context)
@@ -195,7 +194,7 @@ class TestControllerIntegration:
goto_action = {'go_to_url': GoToUrlAction(url='https://yahoo.com')}
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
await controller.act(GoToUrlActionModel(**goto_action), browser_context)
@@ -215,7 +214,7 @@ class TestControllerIntegration:
input_action = {'input_text': InputTextAction(index=mock_input_index, text='Python programming')}
class InputTextActionModel(ActionModel):
- input_text: Optional[InputTextAction] = None
+ input_text: InputTextAction | None = None
# The actual input might fail if the page structure changes or in headless mode
# So we'll just verify the controller correctly processes the action
@@ -235,7 +234,7 @@ class TestControllerIntegration:
invalid_action = {'click_element_by_index': ClickElementAction(index=9999)}
class ClickActionModel(ActionModel):
- click_element_by_index: Optional[ClickElementAction] = None
+ click_element_by_index: ClickElementAction | None = None
# This should fail since the element doesn't exist
with pytest.raises(Exception) as excinfo:
@@ -251,7 +250,7 @@ class TestControllerIntegration:
wait_action = {'wait': {'seconds': 1}} # Corrected format
class WaitActionModel(ActionModel):
- wait: Optional[dict] = None
+ wait: dict | None = None
# Record start time
start_time = time.time()
@@ -276,7 +275,7 @@ class TestControllerIntegration:
goto_action1 = {'go_to_url': GoToUrlAction(url='https://google.com')}
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
await controller.act(GoToUrlActionModel(**goto_action1), browser_context)
@@ -299,7 +298,7 @@ class TestControllerIntegration:
go_back_action = {'go_back': NoParamsAction()}
class GoBackActionModel(ActionModel):
- go_back: Optional[NoParamsAction] = None
+ go_back: NoParamsAction | None = None
result = await controller.act(GoBackActionModel(**go_back_action), browser_context)
@@ -329,7 +328,7 @@ class TestControllerIntegration:
action_data = {'go_to_url': GoToUrlAction(url=url)}
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
await controller.act(GoToUrlActionModel(**action_data), browser_context)
@@ -342,7 +341,7 @@ class TestControllerIntegration:
go_back_action = {'go_back': NoParamsAction()}
class GoBackActionModel(ActionModel):
- go_back: Optional[NoParamsAction] = None
+ go_back: NoParamsAction | None = None
await controller.act(GoBackActionModel(**go_back_action), browser_context)
await asyncio.sleep(1) # Wait for navigation to complete
@@ -360,7 +359,7 @@ class TestControllerIntegration:
goto_action1 = {'go_to_url': GoToUrlAction(url=urls[0])}
class GoToUrlActionModel(ActionModel):
- go_to_url: Optional[GoToUrlAction] = None
+ go_to_url: GoToUrlAction | None = None
await controller.act(GoToUrlActionModel(**goto_action1), browser_context)
@@ -368,7 +367,7 @@ class TestControllerIntegration:
open_tab_action = {'open_tab': OpenTabAction(url=urls[1])}
class OpenTabActionModel(ActionModel):
- open_tab: Optional[OpenTabAction] = None
+ open_tab: OpenTabAction | None = None
await controller.act(OpenTabActionModel(**open_tab_action), browser_context)
@@ -380,7 +379,7 @@ class TestControllerIntegration:
switch_tab_action = {'switch_tab': SwitchTabAction(page_id=0)}
class SwitchTabActionModel(ActionModel):
- switch_tab: Optional[SwitchTabAction] = None
+ switch_tab: SwitchTabAction | None = None
await controller.act(SwitchTabActionModel(**switch_tab_action), browser_context)
@@ -392,7 +391,7 @@ class TestControllerIntegration:
close_tab_action = {'close_tab': CloseTabAction(page_id=1)}
class CloseTabActionModel(ActionModel):
- close_tab: Optional[CloseTabAction] = None
+ close_tab: CloseTabAction | None = None
await controller.act(CloseTabActionModel(**close_tab_action), browser_context)
@@ -408,7 +407,7 @@ class TestControllerIntegration:
search_action = {'search_google': SearchGoogleAction(query='Python web automation')}
class SearchGoogleActionModel(ActionModel):
- search_google: Optional[SearchGoogleAction] = None
+ search_google: SearchGoogleAction | None = None
result = await controller.act(SearchGoogleActionModel(**search_action), browser_context)
diff --git a/tests/test_mind2web.py b/tests/test_mind2web.py
index af07dd5b6..1e8db557d 100644
--- a/tests/test_mind2web.py
+++ b/tests/test_mind2web.py
@@ -5,7 +5,7 @@ Test browser automation using Mind2Web dataset tasks with pytest framework.
import asyncio
import json
import os
-from typing import Any, Dict, List
+from typing import Any
import pytest
from langchain_openai import AzureChatOpenAI
@@ -45,7 +45,7 @@ async def context(browser):
@pytest.fixture(scope='session')
-def test_cases() -> List[Dict[str, Any]]:
+def test_cases() -> list[dict[str, Any]]:
"""Load test cases from Mind2Web dataset"""
file_path = os.path.join(os.path.dirname(__file__), 'mind2web_data/processed.json')
logger.info(f'Loading test cases from {file_path}')
@@ -73,7 +73,7 @@ def llm():
# run with: pytest -s -v tests/test_mind2web.py:test_random_samples
@pytest.mark.asyncio
-async def test_random_samples(test_cases: List[Dict[str, Any]], llm, context, validator):
+async def test_random_samples(test_cases: list[dict[str, Any]], llm, context, validator):
"""Test a random sampling of tasks across different websites"""
import random