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
New clean up
magmueller63a26bd37489
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex 0d7023779..584c889d0 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -12,7 +12,11 @@ class BrowserActions:def execute_action(self, action: dict):print(action.keys())action_name = action["action"]- params = action["params"]++ if "params" in action:+ params = action["params"]+ else:+ params = {}if action_name == "search_google":self.search_google(params["query"])@@ -26,6 +30,8 @@ class BrowserActions:self.input_text_by_c(params["c"], params["text"])elif action_name == "click":self.click_element_by_c(params["c"])+ elif action_name == "accept_cookies":+ self.driver.accept_cookies()else:raise Exception(f"Action {action_name} not found")@@ -81,4 +87,5 @@ class BrowserActions:"go_back": "","click": "c: int","input": "c: int, text: string",+ "accept_cookies": "",}diff --git a/src/state_manager/state.py b/src/state_manager/state.pyindex 9e0eccbf3..380b1fde5 100644--- a/src/state_manager/state.py+++ b/src/state_manager/state.py@@ -19,14 +19,13 @@ class StateManager:Dict: Current state including URL, page title, and interactable elements"""html_content = self.driver.page_source- cleaned_html = cleanup_html(html_content)- main_content = self.get_main_content()+ cleaned_content = cleanup_html(html_content)+return {"current_url": self.driver.current_url,"page_title": self.driver.title,- "interactable_elements": cleaned_html,- "main_content": main_content,- # "functions": functions+ "interactable_elements": cleaned_content["html"],+ # "main_content": cleaned_content["main_content"]}def get_functions(self) -> List[Dict]:diff --git a/src/state_manager/utils.py b/src/state_manager/utils.pyindex 01ea06dda..0c98d84f3 100644--- a/src/state_manager/utils.py+++ b/src/state_manager/utils.py@@ -1,12 +1,151 @@from bs4 import BeautifulSoup-from bs4 import BeautifulSoup, Comment, Tagimport reimport os+from bs4 import Comment, Tagdef cleanup_html(html_content):"""Clean up html content by removing unnecessary HTML elements and formatting.+ Returns a dictionary with cleaned HTML and main content.+ """+ if not html_content:+ return {"html": "", "main_content": ""}++ soup = BeautifulSoup(html_content, "html.parser")+ class_counter = 0++ # Extract main content before cleaning+ main_content = ""+ main_element = soup.find('main') or soup.find(id='main')+ if main_element:+ main_content = main_element.get_text(strip=True)+ else:+ # If no main element, try to get content from body+ content_containers = soup.select('div[role="main"], div.content, div#content, article, .main-content')+ if content_containers:+ main_content = content_containers[0].get_text(strip=True)+ else:+ # Fallback to body text if no specific content container found+ body = soup.find('body')+ if body:+ main_content = body.get_text(strip=True)++ # Remove hidden elements and unnecessary content+ for element in soup.find_all():+ if element is None:+ continue++ # Remove if element is hidden+ if hasattr(element, 'attrs') and element.attrs and (+ element.get('aria-hidden') == 'true' or+ element.get('hidden') or+ element.get('style') and ('display: none' in element.get('style') or 'visibility: hidden' in element.get('style')) or+ element.get('class') and ('hidden' in ' '.join(element.get('class')) or+ 'invisible' in ' '.join(element.get('class')))):+ element.decompose()+ continue++ # Remove all non-essential elements+ if element.name in ['script', 'style', 'noscript', 'iframe', 'link', 'meta',+ 'head', 'svg', 'path', 'defs', 'clipPath']:+ element.decompose()+ continue++ # Find and clean interactive elements+ interactive_selectors = [+ "button", "a", "input", "select", "textarea",+ "[role='button']", "[role='link']", "[role='combobox']",+ "[tabindex='0']", "[aria-haspopup]",+ "[class*='modal']", "[class*='popup']", "[class*='overlay']",+ "[id*='cookie']", "[class*='cookie']", "[aria-label*='cookie']"+ ]++ # First pass: mark overlay/popup elements+ overlay_elements = []+ for selector in interactive_selectors[9:]: # Only popup/overlay selectors+ for element in soup.select(selector):+ if element and not element.get('c'):+ element["c"] = str(class_counter)+ class_counter += 1+ overlay_elements.append(element)++ # Second pass: mark other interactive elements if no overlays found+ if not overlay_elements:+ for selector in interactive_selectors[:9]: # Non-popup selectors+ for element in soup.select(selector):+ if element is None or element.get('c'):+ continue++ # Check if element is visible+ if hasattr(element, 'attrs') and element.attrs and (+ element.get('aria-hidden') == 'true' or+ element.get('hidden') or+ element.get('style') and ('display: none' in element.get('style'))):+ continue++ # Add c attribute to interactive element+ element["c"] = str(class_counter)+ class_counter += 1++ # Clean up attributes+ for element in soup.find_all():+ if element and element.get('c'):+ # Keep only essential attributes+ allowed_attrs = ["c", "href", "aria-label", "placeholder", "id", "type"]+ attrs = dict(element.attrs)+ for attr in attrs:+ if attr not in allowed_attrs:+ del element[attr]++ # Get the HTML string and clean it up+ cleaned_html = str(soup)+ cleaned_html = " ".join(cleaned_html.split())++ # Remove empty tags with regex+ empty_tags_pattern = r"<[^/>][^>]*></[^>]+>"+ while re.search(empty_tags_pattern, cleaned_html):+ cleaned_html = re.sub(empty_tags_pattern, "", cleaned_html)++ return {+ "html": cleaned_html,+ "main_content": main_content+ }+++def save_formatted_html(html_content, output_file_name):+ """+ Format HTML content using BeautifulSoup and save to file++ Args:+ html_content (str): Raw HTML content to format+ output_file_name (str): Name of the file where formatted HTML will be saved+ """+ # Format HTML with BeautifulSoup for nice indentation+ soup = BeautifulSoup(html_content, 'html.parser')+ formatted_html = soup.prettify()++ # create temp folder if it doesn't exist+ if not os.path.exists("temp"):+ os.makedirs("temp")++ # Save formatted HTML to file+ with open("temp/"+output_file_name, 'w', encoding='utf-8') as f:+ f.write(formatted_html)+++def save_markdown(markdown_content, output_file_name):+ """Save markdown content to a file"""+ if not os.path.exists("temp"):+ os.makedirs("temp")++ with open("temp/"+output_file_name, 'w', encoding='utf-8') as f:+ f.write(markdown_content)+++def cleanup_html_old(html_content):+ """+ Clean up html content by removing unnecessary HTML elements and formatting.Args:html_content (str): Raw HTML content to clean@@ -88,32 +227,3 @@ def cleanup_html(html_content):cleaned_html = re.sub(empty_tags_pattern, "", cleaned_html)return cleaned_html---# Format and save HTML content to file---def save_formatted_html(html_content, output_file_name):- """- Format HTML content using BeautifulSoup and save to file-- Args:- html_content (str): Raw HTML content to format- output_file_name (str): Name of the file where formatted HTML will be saved- """- # Format HTML with BeautifulSoup for nice indentation- soup = BeautifulSoup(html_content, 'html.parser')- formatted_html = soup.prettify()-- # create temp folder if it doesn't exist- if not os.path.exists("temp"):- os.makedirs("temp")-- # Save formatted HTML to file- with open("temp/"+output_file_name, 'w', encoding='utf-8') as f:- f.write(formatted_html)---def save_markdown(markdown_content, output_file_name):- with open("temp/"+output_file_name, 'w', encoding='utf-8') as f:- f.write(markdown_content)diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex e9919b8fe..9fe883445 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -29,9 +29,11 @@ class TestKayakSearch(unittest.TestCase):max_steps = 10for i in range(max_steps):# Get current state+ input("\n\n\nPress Enter to continue...")+current_state = self.state_manager.get_current_state()save_formatted_html(current_state["interactable_elements"], f"current_state_{i}.html")- save_markdown(current_state["main_content"], f"current_state_{i}.md")+ # save_markdown(current_state["main_content"], f"current_state_{i}.md")# Get next action from agenttext = f"Current state: {current_state}"print(f"\n{text}\n")@@ -44,11 +46,6 @@ class TestKayakSearch(unittest.TestCase):print("Task completed")break- # wait for 1 second- # time.sleep(4)- # wait until i hit enter in the console- input("\n\n\nPress Enter to continue...")-else:self.fail("Failed to complete flight search task in maximum steps")diff --git a/src/utils/selenium_utils.py b/src/utils/selenium_utils.pyindex 4ae29ee5b..b45b46723 100644--- a/src/utils/selenium_utils.py+++ b/src/utils/selenium_utils.py@@ -2,6 +2,9 @@ from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.chrome.service import Servicefrom webdriver_manager.chrome import ChromeDriverManager+from selenium.webdriver.support.ui import WebDriverWait+from selenium.webdriver.support import expected_conditions as EC+from selenium.webdriver.common.by import Bydef setup_selenium_driver(headless: bool = False) -> webdriver.Chrome:@@ -30,4 +33,78 @@ def setup_selenium_driver(headless: bool = False) -> webdriver.Chrome:options=chrome_options)+ # Add cookie acceptance function+ def accept_cookies(driver):+ """+ More robust cookie acceptance function that tries multiple approaches+ """+ try:+ # Common cookie accept button selectors+ cookie_selectors = [+ "button[id*='cookie-accept']",+ "button[id*='accept-cookie']",+ "button[class*='cookie-accept']",+ "button[class*='accept-cookie']",+ "[aria-label*='accept' i][role='button']",+ "[aria-label*='cookie' i][role='button']",+ "button:contains('Accept')",+ "button:contains('Akzeptieren')",+ "button:contains('Zustimmen')",+ "button:contains('Alle akzeptieren')",+ "#onetrust-accept-btn-handler",+ "#accept-all-cookies",+ ".accept-cookies",+ ".accept-all-cookies"+ ]++ wait = WebDriverWait(driver, 10)++ # Try each selector+ for selector in cookie_selectors:+ try:+ # Try to find element by CSS selector+ cookie_button = wait.until(+ EC.element_to_be_clickable((By.CSS_SELECTOR, selector))+ )+ cookie_button.click()+ return True+ except:+ try:+ # Try to find element by XPath containing text+ xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{selector.lower()}')]"+ cookie_button = wait.until(+ EC.element_to_be_clickable((By.XPATH, xpath))+ )+ cookie_button.click()+ return True+ except:+ continue++ # Try finding iframe with cookie consent+ iframes = driver.find_elements(By.TAG_NAME, "iframe")+ for iframe in iframes:+ try:+ driver.switch_to.frame(iframe)+ for selector in cookie_selectors:+ try:+ cookie_button = wait.until(+ EC.element_to_be_clickable((By.CSS_SELECTOR, selector))+ )+ cookie_button.click()+ driver.switch_to.default_content()+ return True+ except:+ continue+ driver.switch_to.default_content()+ except:+ driver.switch_to.default_content()+ continue++ except Exception as e:+ print(f"Error accepting cookies: {str(e)}")+ return False++ # Attach the function to the driver instance+ driver.accept_cookies = lambda: accept_cookies(driver)+return driver