Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
removed random unnecesary functions from controller
Gregor Žunič922ad08fd71c
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 17d212ebb..6e0661dc6 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -1,5 +1,4 @@import asyncio-import datetimeimport enumimport jsonimport logging@@ -18,7 +17,6 @@ from browser_use.browser.context import BrowserContextfrom browser_use.controller.registry.service import Registryfrom browser_use.controller.views import (ClickElementAction,- ClickElementBySelectorAction,CloseTabAction,DoneAction,DragDropAction,@@ -31,7 +29,6 @@ from browser_use.controller.views import (SearchGoogleAction,SendKeysAction,SwitchTabAction,- WaitForElementAction,)from browser_use.utils import time_execution_sync@@ -55,7 +52,7 @@ class Controller(Generic[Context]):# Create a new model that extends the output model with success parameterclass ExtendedOutputModel(BaseModel): # type: ignoresuccess: bool = True- data: output_model+ data: output_model # type: ignore@self.registry.action('Complete task - with return text and if the task is finished (success=True) or not yet completely finished (success=False), because last step is reached',@@ -117,19 +114,6 @@ class Controller(Generic[Context]):await asyncio.sleep(seconds)return ActionResult(extracted_content=msg, include_in_memory=True)- @self.registry.action('Wait for element to be visible', param_model=WaitForElementAction)- async def wait_for_element(params: WaitForElementAction, browser: BrowserContext):- """Waits for the element specified by the CSS selector to become visible within the given timeout."""- try:- await browser.wait_for_element(params.selector, params.timeout)- msg = f'👀 Element with selector "{params.selector}" became visible within {params.timeout}ms.'- logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)- except Exception as e:- err_msg = f'❌ Failed to wait for element "{params.selector}" within {params.timeout}ms: {str(e)}'- logger.error(err_msg)- raise Exception(err_msg)-# Element Interaction Actions@self.registry.action('Click element by index', param_model=ClickElementAction)async def click_element_by_index(params: ClickElementAction, browser: BrowserContext):@@ -168,29 +152,6 @@ class Controller(Generic[Context]):logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')return ActionResult(error=str(e))- @self.registry.action('Click element by selector', param_model=ClickElementBySelectorAction)- async def click_element_by_selector(params: ClickElementBySelectorAction, browser: BrowserContext):- try:- element_node = await browser.get_locate_element_by_css_selector(params.css_selector)- if element_node:- try:- is_hidden = await element_node.is_hidden()- if not is_hidden:- await element_node.scroll_into_view_if_needed()- await element_node.click(timeout=1500, force=True)- except Exception:- try:- # Handle with js evaluate if fails to click using playwright- await element_node.evaluate('el => el.click()')- except Exception as e:- logger.warning(f"Element not clickable with css selector '{params.css_selector}' - {e}")- return ActionResult(error=str(e))- msg = f'🖱️ Clicked on element with text "{params.css_selector}"'- return ActionResult(extracted_content=msg, include_in_memory=True)- except Exception as e:- logger.warning(f'Element not clickable with selector {params.css_selector} - most likely the page changed')- return ActionResult(error=str(e))-@self.registry.action('Input text into a input interactive element',param_model=InputTextAction,@@ -219,7 +180,7 @@ class Controller(Generic[Context]):slug = re.sub(r'[^a-zA-Z0-9]+', '-', short_url).strip('-').lower()sanitized_filename = f'{slug}.pdf'- await page.emulate_media('screen')+ await page.emulate_media(media='screen')await page.pdf(path=sanitized_filename, format='A4', print_background=False)msg = f'Saving page with URL {page.url} as PDF to ./{sanitized_filename}'logger.info(msg)@@ -288,36 +249,6 @@ class Controller(Generic[Context]):logger.info(msg)return ActionResult(extracted_content=msg)- # HTML Download- @self.registry.action(- 'Save the raw HTML content of the current page to a local file',- param_model=NoParamsAction,- )- async def save_html_to_file(_: NoParamsAction, browser: BrowserContext) -> ActionResult:- """Retrieves and returns the full HTML content of the current page to a file"""- try:- page = await browser.get_current_page()- html_content = await page.content()-- # Create a filename based on the page URL- short_url = re.sub(r'^https?://(?:www\.)?|/$', '', page.url)- slug = re.sub(r'[^a-zA-Z0-9]+', '-', short_url).strip('-').lower()[:64]- timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')- sanitized_filename = f'{slug}_{timestamp}.html'-- # Save HTML to file- with open(sanitized_filename, 'w', encoding='utf-8') as f:- f.write(html_content)-- msg = f'Saved HTML content of page with URL {page.url} to ./{sanitized_filename}'-- logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)- except Exception as e:- error_msg = f'Failed to save HTML content: {str(e)}'- logger.error(error_msg)- return ActionResult(error=error_msg, extracted_content='')-@self.registry.action('Scroll down the page by pixel amount - if no amount is specified, scroll down one page',param_model=ScrollAction,diff --git a/browser_use/controller/views.py b/browser_use/controller/views.pyindex e1a4fa49c..04ffb9758 100644--- a/browser_use/controller/views.py+++ b/browser_use/controller/views.py@@ -12,30 +12,11 @@ class GoToUrlAction(BaseModel):url: str-class WaitForElementAction(BaseModel):- selector: str- timeout: Optional[int] = 10000 # Timeout in milliseconds--class ClickElementAction(BaseModel):index: intxpath: Optional[str] = None-class ClickElementByXpathAction(BaseModel):- xpath: str---class ClickElementBySelectorAction(BaseModel):- css_selector: str---class ClickElementByTextAction(BaseModel):- text: str- element_type: Optional[str]- nth: int = 0--class InputTextAction(BaseModel):index: inttext: str