Skip to content

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

Include new cleanup

magmueller4e8df47bab66
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.py
index 85a974c74..13a93368b 100644
--- a/src/actions/browser_actions.py
+++ b/src/actions/browser_actions.py
@@ -1,87 +1,103 @@
from selenium import webdriver
from selenium.webdriver.common.by import By
-from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import WebDriverWait
class BrowserActions:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
- self.wait = WebDriverWait(driver, 10)
+ def __init__(self, driver: webdriver.Chrome):
+ self.driver = driver
+ self.wait = WebDriverWait(driver, 10)
+ self.selector_map = {} # Will store current selector map
+
+ def update_selector_map(self, selector_map: dict):
+ """Update the current selector map"""
+ self.selector_map = selector_map
+
+ def execute_action(self, action: dict, selector_map: dict):
+ print(action.keys())
+ action_name = action['action']
+ self.update_selector_map(selector_map)
+
+ if 'params' in action:
+ params = action['params']
+ else:
+ params = {}
+
+ if action_name == 'search_google':
+ self.search_google(params['query'])
+ elif action_name == 'nothing':
+ pass
+ elif action_name == 'go_to_url':
+ self.go_to_url(params['url'])
+ elif action_name == 'go_back':
+ self.go_back()
+ elif action_name == 'done':
+ return True
+ elif action_name == 'input':
+ self.input_text_by_index(params['id'], params['text'])
+ elif action_name == 'click':
+ self.click_element_by_index(params['id'])
+ # elif action_name == 'accept_cookies':
+ # self.driver.accept_cookies()
+ else:
+ raise Exception(f'Action {action_name} not found')
- def execute_action(self, action: dict):
- print(action.keys())
- action_name = action['action']
+ def click_element_by_index(self, index: int):
+ """
+ Clicks an element using its index from the selector map.
+ """
+ if str(index) not in self.selector_map:
+ raise Exception(f'Element index {index} not found in selector map')
- if 'params' in action:
- params = action['params']
- else:
- params = {}
+ xpath = self.selector_map[str(index)]
+ element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
+ element.click()
- if action_name == 'search_google':
- self.search_google(params['query'])
- elif action_name == 'go_to_url':
- self.go_to_url(params['url'])
- elif action_name == 'go_back':
- self.go_back()
- elif action_name == 'done':
- return True
- elif action_name == 'input':
- 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')
+ def input_text_by_index(self, index: int, text: str):
+ """
+ Inputs text into a field using its index from the selector map.
+ """
+ if str(index) not in self.selector_map:
+ raise Exception(f'Element index {index} not found in selector map')
- # default actions
- def search_google(self, query: str):
- """
- Performs a Google search with the provided query.
- """
- # TODO: replace with search api
- self.driver.get('https://www.google.com')
- search_box = self.wait.until(EC.presence_of_element_located((By.NAME, 'q')))
- search_box.send_keys(query)
- search_box.submit()
+ xpath = self.selector_map[str(index)]
+ element = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
+ element.clear()
+ element.send_keys(text)
- def go_to_url(self, url: str):
- """
- Navigates the browser to the specified URL.
- """
- self.driver.get(url)
+ # default actions
+ def search_google(self, query: str):
+ """
+ Performs a Google search with the provided query.
+ """
+ # TODO: replace with search api
+ self.driver.get('https://www.google.com')
- def go_back(self):
- """
- Navigates back in the browser history.
- """
- self.driver.back()
+ search_box = self.wait.until(EC.presence_of_element_located((By.NAME, 'q')))
+ search_box.send_keys(query)
+ search_box.submit()
- def click_element_by_c(self, c_value: str):
- """
- Clicks an element identified by its c attribute.
- """
- element = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, f'[c="{c_value}"]')))
- element.click()
+ def go_to_url(self, url: str):
+ """
+ Navigates the browser to the specified URL.
+ """
+ self.driver.get(url)
- def input_text_by_c(self, c_value: str, text: str):
- """
- Inputs text into a field identified by its c attribute.
- """
- element = self.wait.until(
- EC.presence_of_element_located((By.CSS_SELECTOR, f'[c="{c_value}"]'))
- )
- element.clear()
- element.send_keys(text)
+ def go_back(self):
+ """
+ Navigates back in the browser history.
+ """
+ self.driver.back()
- def get_default_actions(self) -> dict[str, str]:
- return {
- 'search_google': 'query: string',
- 'go_to_url': 'url: string',
- 'done': '',
- 'go_back': '',
- 'click': 'c: int',
- 'input': 'c: int, text: string',
- 'accept_cookies': '',
- }
+ def get_default_actions(self) -> dict[str, str]:
+ return {
+ 'search_google': 'query: string',
+ 'go_to_url': 'url: string',
+ 'done': '',
+ 'go_back': '',
+ 'click': 'id: int',
+ 'input': 'id: int, text: string',
+ 'nothing': '',
+ }
+ # 'accept_cookies': '',
diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.py
index 75fa19d26..6853656f8 100644
--- a/src/agent_interface/planing_agent.py
+++ b/src/agent_interface/planing_agent.py
@@ -1,64 +1,91 @@
-from typing import Dict, List, Optional
import json
import os
-from openai import OpenAI
+from typing import Dict
+
from dotenv import load_dotenv
+from openai import OpenAI
from tokencost import calculate_prompt_cost, count_string_tokens
class PlaningAgent:
- def __init__(self, task: str, default_actions: str):
- load_dotenv()
- self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
- self.model = 'gpt-4o'
- self.messages = [
- {'role': 'system', 'content': self.get_system_prompt(task, default_actions)}
- ]
-
- def chat(self, task: str) -> Dict:
- # TODO: include state, actions, etc.
-
- # select next functions to call
- messages = self.messages + [{'role': 'user', 'content': task}]
-
- # Calculate total cost for all messages
- total_cost = calculate_prompt_cost(messages, self.model)
- total_tokens = count_string_tokens(' '.join([m['content'] for m in messages]), self.model)
- print(
- 'Total prompt cost: ',
- f'${total_cost:,.2f}',
- 'Total tokens: ',
- f'{total_tokens:,}',
- )
-
- response = self.client.chat.completions.create(
- model=self.model, messages=messages, response_format={'type': 'json_object'}
- )
-
- # Only append the output message
- self.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})
-
- # parse the response
- return json.loads(response.choices[0].message.content)
-
- def get_system_prompt(self, task: str, default_actions: str) -> str:
- # System prompts for the agent
- output_format = """
- {"action": "action_name", "params": {"param_name": "param_value"}}
+ def __init__(self, task: str, default_actions: str):
+ load_dotenv()
+ self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
+ self.model = 'gpt-4o'
+ self.messages = [
+ {'role': 'system', 'content': self.get_system_prompt(task, default_actions)}
+ ]
+
+ def chat(self, task: str, skip_call: bool = False) -> Dict:
+ # TODO: include state, actions, etc.
+
+ # select next functions to call
+ messages = self.messages + [{'role': 'user', 'content': task}]
+
+ # Calculate total cost for all messages
+ total_cost = calculate_prompt_cost(messages, self.model)
+ total_tokens = count_string_tokens(' '.join([m['content'] for m in messages]), self.model)
+ print(
+ 'Total prompt cost: ',
+ f'${total_cost:,.2f}',
+ 'Total tokens: ',
+ f'{total_tokens:,}',
+ )
+
+ if skip_call:
+ return {'action': 'nothing'}
+
+ response = self.client.chat.completions.create(
+ model=self.model, messages=messages, response_format={'type': 'json_object'}
+ )
+
+ # Only append the output message
+ self.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})
+
+ return json.loads(response.choices[0].message.content)
+
+ def get_system_prompt(self, task: str, default_actions: str) -> str:
"""
+ Get the system prompt for the agent.
- AGENT_PROMPT = f"""
- You are a web scraping agent. Your task is to control the browser where, for every step,
- you get the current state and a list of actions you can take as dictionary.
- If you want to click on an element or input text, you need to specify the element id (c="") from the cleaned HTML.
- You have to select the next action in json format:
- {output_format}
+ Args:
+ task: The task description
+ default_actions: Available default actions
+
+ Returns:
+ str: Formatted system prompt
+ """
+ # System prompts for the agent
+ output_format = """
+ {"action": "action_name", "params": {"param_name": "param_value"}}
+ """
- Your task is:
- {task}
+ AGENT_PROMPT = f"""
+ You are an AI agent that helps users navigate websites and perform actions. Your task is: {task}
Available actions:
{default_actions}
+
+ The page content will be provided as numbered elements like this:
+ 0:<button>Click me</button>
+ 1:<a href="/test">Link text</a>
+ 2:Some visible text content
+
+ To interact with elements, use their index number in the click() or input() actions.
+ Each element has a unique index that can be used to interact with it.
+
+ Provide your next action based on the available actions and visible elements.
+ Respond with a valid JSON object containing the action and any required parameters.
+
+ Response format:
+ {output_format}
+
"""
- return AGENT_PROMPT
+ return AGENT_PROMPT
+
+ # Remember:
+ # 1. Always check if elements exist before trying to interact with them
+ # 2. Use the exact index numbers shown in the elements list
+ # 3. If you need to accept cookies, use the accept_cookies action first
+ # 4. If you can't find what you're looking for, consider scrolling or navigating to a different page
diff --git a/src/state_manager/state.py b/src/state_manager/state.py
index 1a7719301..160508dc3 100644
--- a/src/state_manager/state.py
+++ b/src/state_manager/state.py
@@ -1,56 +1,54 @@
-from selenium import webdriver
-from selenium.webdriver.common.by import By
from typing import Dict, List
-from bs4 import BeautifulSoup
-from src.state_manager.utils import cleanup_html
+
import requests
-from main_content_extractor import MainContentExtractor
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+
+from src.dom.service import DomService
class StateManager:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
-
- def get_current_state(self) -> Dict:
- """
- Retrieves current URL and interactable elements from cleaned HTML.
-
- Returns:
- Dict: Current state including URL, page title, and interactable elements
- """
- html_content = self.driver.page_source
- cleaned_content = cleanup_html(html_content)
-
- return {
- 'current_url': self.driver.current_url,
- 'page_title': self.driver.title,
- 'interactable_elements': cleaned_content['html'],
- # "main_content": cleaned_content["main_content"]
- }
-
- def get_functions(self) -> List[Dict]:
- """
- Retrieves available functions from cleaned HTML.
- """
- return []
-
- def get_main_content(self) -> str:
- """
- Retrieves main content from cleaned Markdown.
- """
- try:
- # Get HTML using requests
- response = requests.get(self.driver.current_url)
- response.encoding = 'utf-8'
- content = response.text
-
- # Get HTML with main content extracted from HTML
- # extracted_html = MainContentExtractor.extract(content)
-
- # Get HTML with main content extracted from Markdown
- extracted_markdown = MainContentExtractor.extract(content, output_format='markdown')
-
- return extracted_markdown
- except Exception as e:
- print(f'Error getting main content: {e}')
- return ''
+ def __init__(self, driver: webdriver.Chrome):
+ self.driver = driver
+ self.dom_service = DomService()
+
+ def get_current_state(self) -> Dict:
+ """
+ Retrieves current URL and interactable elements from processed HTML.
+
+ Returns:
+ Dict: Current state including URL, page title, interactable elements and selector map
+ """
+ html_content = self.driver.page_source
+ processed_content = self.dom_service.process_content(html_content)
+
+ return {
+ 'current_url': self.driver.current_url,
+ 'page_title': self.driver.title,
+ 'interactable_elements': processed_content.output_string,
+ 'selector_map': processed_content.selector_map
+ }
+
+ def get_functions(self) -> List[Dict]:
+ """
+ Retrieves available functions from cleaned HTML.
+ """
+ return []
+
+ def get_main_content(self) -> str:
+ """
+ Retrieves main content from the page.
+ """
+ try:
+ # Get HTML using requests
+ response = requests.get(self.driver.current_url)
+ response.encoding = 'utf-8'
+ content = response.text
+
+ # Process content using DomService
+ processed_content = self.dom_service.process_content(content)
+ return processed_content.output_string
+
+ except Exception as e:
+ print(f'Error getting main content: {e}')
+ return ''
diff --git a/src/tests/test_html_cleanup.py b/src/tests/test_html_cleanup.py
deleted file mode 100644
index b3ca42578..000000000
--- a/src/tests/test_html_cleanup.py
+++ /dev/null
@@ -1,139 +0,0 @@
-import unittest
-from bs4 import BeautifulSoup
-from src.state_manager.utils import cleanup_html
-import os
-
-
-class TestHTMLCleanup(unittest.TestCase):
- def setUp(self):
- # Create test directory if it doesn't exist
- self.test_dir = 'test_files'
- if not os.path.exists(self.test_dir):
- os.makedirs(self.test_dir)
-
- def test_cleanup_sample_html(self):
- # Sample HTML with various elements to test
- test_html = """
- <html>
- <head>
- <script>Some script</script>
- <style>Some style</style>
- </head>
- <body>
- <div class="hidden">Hidden content</div>
- <div style="display: none">Display none content</div>
- <div aria-hidden="true">Aria hidden content</div>
- <button class="interactive" onclick="test()">Click me</button>
- <a href="/test" class="link">Link text</a>
- <div class="content">Visible content</div>
- <input type="text" placeholder="Enter text">
- <select>
- <option>Option 1</option>
- </select>
- <div role="button">Custom button</div>
- <div class="cookie-banner">Accept cookies</div>
- </body>
- </html>
- """
-
- result = cleanup_html(test_html)
- cleaned_html = result['html']
-
- # Parse the cleaned HTML for testing
- soup = BeautifulSoup(cleaned_html, 'html.parser')
-
- # Test that script and style are removed
- self.assertEqual(len(soup.find_all('script')), 0)
- self.assertEqual(len(soup.find_all('style')), 0)
-
- # Test that hidden elements are removed
- self.assertEqual(len(soup.find_all(attrs={'class': 'hidden'})), 0)
- self.assertEqual(len(soup.find_all(attrs={'style': 'display: none'})), 0)
- self.assertEqual(len(soup.find_all(attrs={'aria-hidden': 'true'})), 0)
-
- # Test that interactive elements have 'c' attribute
- interactive_elements = soup.find_all(attrs={'c': True})
- self.assertGreater(len(interactive_elements), 0)
-
- # Test specific interactive elements
- self.assertIsNotNone(soup.find('button'))
- self.assertIsNotNone(soup.find('a'))
- self.assertIsNotNone(soup.find('input'))
- self.assertIsNotNone(soup.find('select'))
-
- # Print cleaned HTML for inspection
- print('\nCleaned HTML:')
- print(cleaned_html)
-
- def test_cleanup_real_page(self):
- # Load a real webpage HTML file
- test_file = os.path.join(self.test_dir, 'kayak_page.html')
-
- # First run: download and save the page if it doesn't exist
- if not os.path.exists(test_file):
- import requests
-
- response = requests.get('https://www.kayak.ch')
- with open(test_file, 'w', encoding='utf-8') as f:
- f.write(response.text)
-
- # Read the test file
- with open(test_file, 'r', encoding='utf-8') as f:
- html_content = f.read()
-
- # Clean up the HTML
- result = cleanup_html(html_content)
- cleaned_html = result['html']
-
- # Parse the cleaned HTML
- soup = BeautifulSoup(cleaned_html, 'html.parser')
-
- # Test basic cleanup
- self.assertEqual(len(soup.find_all('script')), 0)
- self.assertEqual(len(soup.find_all('style')), 0)
-
- # Test interactive elements
- interactive_elements = soup.find_all(attrs={'c': True})
- self.assertGreater(len(interactive_elements), 0)
-
- # Print statistics
- print('\nReal page cleanup statistics:')
- print(f'Total interactive elements found: {len(interactive_elements)}')
- print(f"Buttons: {len(soup.find_all('button'))}")
- print(f"Links: {len(soup.find_all('a'))}")
- print(f"Inputs: {len(soup.find_all('input'))}")
- print(f"Selects: {len(soup.find_all('select'))}")
-
- # Save cleaned HTML for manual inspection
- cleaned_file = os.path.join(self.test_dir, 'kayak_page_cleaned.html')
- with open(cleaned_file, 'w', encoding='utf-8') as f:
- f.write(cleaned_html)
- print(f'\nCleaned HTML saved to: {cleaned_file}')
-
- def test_main_content_extraction(self):
- test_html = """
- <html>
- <body>
- <header>Header content</header>
- <main>
- <h1>Main Title</h1>
- <p>Main content paragraph</p>
- <div class="important">Important content</div>
- </main>
- <footer>Footer content</footer>
- </body>
- </html>
- """
-
- result = cleanup_html(test_html)
- main_content = result['main_content']
-
- self.assertIn('Main Title', main_content)
- self.assertIn('Main content paragraph', main_content)
- self.assertIn('Important content', main_content)
- self.assertNotIn('Header content', main_content)
- self.assertNotIn('Footer content', main_content)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index 6f1b4ada3..53ba3d7a2 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -1,54 +1,56 @@
-import unittest
import time
-from src.utils.selenium_utils import setup_selenium_driver
+import unittest
+
from src.actions.browser_actions import BrowserActions
+from src.agent_interface.planing_agent import PlaningAgent
from src.state_manager.state import StateManager
from src.state_manager.utils import save_formatted_html, save_markdown
-from src.agent_interface.planing_agent import PlaningAgent
+from src.utils.selenium_utils import setup_selenium_driver
class TestKayakSearch(unittest.TestCase):
- def setUp(self):
- self.driver = setup_selenium_driver(headless=False)
- self.actions = BrowserActions(self.driver)
- self.state_manager = StateManager(self.driver)
+ def setUp(self):
+ self.driver = setup_selenium_driver(headless=False)
+ self.actions = BrowserActions(self.driver)
+ self.state_manager = StateManager(self.driver)
- def tearDown(self):
- self.driver.quit()
+ def tearDown(self):
+ self.driver.quit()
- def test_kayak_flight_search(self):
- # Define the task
- task = 'Go to directly to the url https://www.kayak.ch/ and look there for flights from Zurich to New York for Nov 5th, 2024 for 2 people'
+ def test_kayak_flight_search(self):
+ # Define the task
+ task = 'Go to directly to the url https://www.kayak.ch/ and look there for flights from Zurich to New York for Nov 5th, 2024 for 2 people'
- default_actions = self.actions.get_default_actions()
- print(f'Default actions: {default_actions}')
+ default_actions = self.actions.get_default_actions()
+ print(f'Default actions: {default_actions}')
- agent = PlaningAgent(task, default_actions)
+ agent = PlaningAgent(task, default_actions)
- # Main interaction loop
- max_steps = 10
- for i in range(max_steps):
- # Get current state
- input('\n\n\nPress Enter to continue...')
+ # Main interaction loop
+ max_steps = 10
+ for 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")
- # Get next action from agent
- text = f'Current state: {current_state}'
- print(f'\n{text}\n')
+ current_state = self.state_manager.get_current_state()
+ save_formatted_html(current_state['interactable_elements'], f'current_state_{i}.html')
+ print(f'Current state map: {current_state["selector_map"]}')
+ # save_markdown(current_state["main_content"], f"current_state_{i}.md")
+ # Get next action from agent
+ text = f'Elements: {current_state["interactable_elements"]}'
+ print(f'\n{text}\n')
- action = agent.chat(text)
- print(f'Selected action: {action}')
+ action = agent.chat(text, skip_call=True)
+ print(f'Selected action: {action}')
- out = self.actions.execute_action(action)
- if out:
- print('Task completed')
- break
+ out = self.actions.execute_action(action, current_state['selector_map'])
+ if out:
+ print('Task completed')
+ break
- else:
- self.fail('Failed to complete flight search task in maximum steps')
+ else:
+ self.fail('Failed to complete flight search task in maximum steps')
if __name__ == '__main__':
- unittest.main()
+ unittest.main()
diff --git a/src/utils/selenium_utils.py b/src/utils/selenium_utils.py
index b5312a06e..672098807 100644
--- a/src/utils/selenium_utils.py
+++ b/src/utils/selenium_utils.py
@@ -1,107 +1,107 @@
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
-from 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 By
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import WebDriverWait
+from webdriver_manager.chrome import ChromeDriverManager
def setup_selenium_driver(headless: bool = False) -> webdriver.Chrome:
- """
- Sets up and returns a Selenium WebDriver instance.
+ """
+ Sets up and returns a Selenium WebDriver instance.
- Args:
- headless (bool): Whether to run browser in headless mode
+ Args:
+ headless (bool): Whether to run browser in headless mode
- Returns:
- webdriver.Chrome: Configured Chrome WebDriver instance
- """
- # Configure Chrome options
- chrome_options = Options()
- if headless:
- chrome_options.add_argument('--headless')
+ Returns:
+ webdriver.Chrome: Configured Chrome WebDriver instance
+ """
+ # Configure Chrome options
+ chrome_options = Options()
+ if headless:
+ chrome_options.add_argument('--headless')
- # Disable automation flags
- chrome_options.add_argument('--disable-blink-features=AutomationControlled')
- chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
- chrome_options.add_experimental_option('useAutomationExtension', False)
+ # Disable automation flags
+ chrome_options.add_argument('--disable-blink-features=AutomationControlled')
+ chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
+ chrome_options.add_experimental_option('useAutomationExtension', False)
- # Initialize the Chrome driver
- driver = webdriver.Chrome(
- service=Service(ChromeDriverManager().install()), options=chrome_options
- )
+ # Initialize the Chrome driver
+ driver = webdriver.Chrome(
+ service=Service(ChromeDriverManager().install()), 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',
- ]
+ # 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)
+ 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 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
+ # 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
+ 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)
+ # Attach the function to the driver instance
+ driver.accept_cookies = lambda: accept_cookies(driver)
- return driver
+ return driver