Skip to content

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

fixed extraction

Gregor Žuničd8ca10006804
diff --git a/src/browser/service.py b/src/browser/service.py
index 5600fcbbe..bc7c4c4b1 100644
--- a/src/browser/service.py
+++ b/src/browser/service.py
@@ -18,7 +18,7 @@ from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
-from src.browser.views import BrowserException, BrowserState
+from src.browser.views import BrowserState
from src.dom.service import DomService
@@ -45,7 +45,7 @@ class BrowserService:
chrome_options.add_experimental_option('useAutomationExtension', False)
# Additional stealth settings
- chrome_options.add_argument('--start-maximized')
+ chrome_options.add_argument('--window-size=1024,1024')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-infobars')
diff --git a/src/dom/service.py b/src/dom/service.py
index 3c4962261..9c0667a82 100644
--- a/src/dom/service.py
+++ b/src/dom/service.py
@@ -9,6 +9,7 @@ class DomService:
self.driver = driver
def get_clickable_elements(self) -> ProcessedDomContent:
+ # Get current state of DOM by executing JavaScript
html_content = self.driver.page_source
return self._process_content(html_content)
@@ -22,78 +23,46 @@ class DomService:
@dev TODO: instead of of using enumerated index, use random 4 digit numbers -> a bit more tokens BUT updates on the screen wont click on incorrect items -> tricky because you have to consider that same elements need to have the same index ...
"""
+
+ # Parse HTML content using BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
+
candidate_elements: list[Tag | NavigableString] = []
+ dom_queue = [element for element in soup.body.children] if soup.body else []
xpath_cache = {}
- def process_element(element: PageElement) -> bool:
- """
- Process element and its children, return True if this element or any of its
- children were added to candidates
- """
- # Debug cookie consent elements
- if isinstance(element, Tag):
- classes = element.get('class', [])
- if isinstance(classes, str):
- classes = classes.split()
- if 'RxNS' in classes or 'P4zO' in classes:
- print(f'\nDEBUG Cookie Element: {element.name}')
- print(f'Accepted: {self._is_element_accepted(element)}')
- print(f'Interactive: {self._is_interactive_element(element)}')
- if self._is_interactive_element(element):
- print(f'Active: {self._is_active(element)}')
- print(f'Top Element: {self._is_top_element(element)}')
- print(f'Visible: {self._is_visible(element)}')
- print(f'XPath: {self._generate_xpath(element)}\n')
-
- has_selected_children = False
-
- # Handle Tag elements
+ # Find candidate elements
+ while dom_queue:
+ element = dom_queue.pop()
+ should_add_element = False
+
+ # Handle both Tag elements and text nodes
if isinstance(element, Tag):
if not self._is_element_accepted(element):
- element.decompose()
- return False
+ # Skip element if it's not accepted
+ element.decompose() # get rid of some memory leaks potentially
+ continue
- # Process children first (post-order traversal)
for child in element.children:
- if process_element(child):
- has_selected_children = True
+ dom_queue.append(child)
- # Always process interactive elements regardless of children
- is_interactive = self._is_interactive_element(element)
- if is_interactive:
+ # Check if element is interactive or leaf element
+ if self._is_interactive_element(element) or self._is_leaf_element(element):
if (
self._is_active(element)
and self._is_top_element(element)
and self._is_visible(element)
):
- candidate_elements.append(element)
- return True
-
- # For non-interactive elements, only add if it's a leaf and no children were selected
- if (
- not has_selected_children
- and self._is_leaf_element(element)
- and self._is_active(element)
- and self._is_top_element(element)
- and self._is_visible(element)
- ):
- candidate_elements.append(element)
- return True
-
- return has_selected_children
-
- # Handle text nodes
+ should_add_element = True
+
elif isinstance(element, NavigableString) and element.strip():
if self._is_visible(element):
- candidate_elements.append(element)
- return True
+ should_add_element = True
- return False
-
- # Start processing from body
- if soup.body:
- process_element(soup.body)
+ if should_add_element:
+ if not isinstance(element, (Tag, NavigableString)):
+ continue
+ candidate_elements.append(element)
# Process candidates
selector_map: dict[int, str] = {}
@@ -114,7 +83,15 @@ class DomService:
if isinstance(element, NavigableString):
text_content = element.strip()
if text_content:
- output_items.append(DomContentItem(index=index, text=text_content))
+ output_string = f'{text_content}'
+ output_items.append(
+ DomContentItem(index=index, text=output_string, clickable=False)
+ )
+ continue
+ else:
+ # don't add empty text nodes
+ continue
+
else:
text_content = self._extract_text_from_all_children(element)
@@ -124,9 +101,8 @@ class DomService:
opening_tag = f"<{tag_name}{' ' + attributes if attributes else ''}>"
closing_tag = f'</{tag_name}>'
- output_items.append(
- DomContentItem(index=index, text=f'{opening_tag}{text_content}{closing_tag}')
- )
+ output_string = f'{opening_tag}{text_content}{closing_tag}'
+ output_items.append(DomContentItem(index=index, text=output_string, clickable=True))
selector_map[index] = xpath
@@ -162,8 +138,8 @@ class DomService:
'select',
'textarea',
'summary',
- 'dialog',
- # 'div', # added
+ # 'dialog',
+ # 'div',
}
interactive_roles = {
@@ -189,11 +165,10 @@ class DomService:
'treeitem',
'spinbutton',
'tooltip',
- 'dialog', # added
- 'alertdialog', # added
+ # 'dialog', # added
+ # 'alertdialog', # added
'menuitemcheckbox',
'menuitemradio',
- 'option',
}
return (
diff --git a/src/dom/tests/extraction_test.py b/src/dom/tests/extraction_test.py
new file mode 100644
index 000000000..21d1cf682
--- /dev/null
+++ b/src/dom/tests/extraction_test.py
@@ -0,0 +1,57 @@
+import time
+
+import pytest
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import WebDriverWait
+from tokencost import count_string_tokens
+from src.browser.service import BrowserService
+
+from src.dom.service import DomService
+
+
+# @pytest.mark.skip("slow af")
+def test_process_html_file():
+ browser = BrowserService(headless=False)
+
+ driver = browser.init()
+
+ dom_service = DomService(driver)
+
+ # driver.get('https://www.kayak.ch')
+ browser.go_to_url('https://www.kayak.ch')
+ # driver.get('https://google.com/flights')
+
+ # driver.get('https://example.com/')
+
+ # driver.implicitly_wait()
+ time.sleep(3)
+
+ # Wait for accept cookies button to appear
+ # accept_cookies_button = WebDriverWait(driver, 10).until(
+ # EC.presence_of_element_located(
+ # (By.XPATH, '/html/body/div[4]/div/div[2]/div/div/div[3]/div/div[1]/button[1]/div/div')
+ # )
+ # )
+
+ print(dom_service.get_clickable_elements().dom_items_to_string())
+
+ # for item in result.items:
+ # print(item)
+
+ # accept_cookies_button.click()
+
+ # Wait for banner to disappear
+ # time.sleep(1)
+
+ # # Process the HTML file
+ # dom_service = DomService(driver)
+ # result = dom_service.get_clickable_elements()
+
+ # # Add assertions based on expected content of page.html
+ # print(f'Processed DOM content: {result.output_html}')
+ # # print(f'Selector map: {result.selector_map}')
+
+ # print('Tokens:', count_string_tokens(result.output_html, 'gpt-4o'))
+
+ input('Press enter to exit')
diff --git a/src/dom/tests/service.py b/src/dom/tests/service.py
deleted file mode 100644
index 8e7f036ef..000000000
--- a/src/dom/tests/service.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# import time
-
-# import pytest
-# from selenium.webdriver.common.by import By
-# from selenium.webdriver.support import expected_conditions as EC
-# from selenium.webdriver.support.ui import WebDriverWait
-# from tokencost import count_string_tokens
-
-# from src.dom.service import DomService
-
-
-# @pytest.mark.skip
-# def test_process_html_file():
-# driver = DriverService(headless=False).get_driver()
-
-# driver.get('https://www.kayak.ch')
-# # driver.get('https://example.com/')
-
-# # driver.implicitly_wait(5)
-
-# # Wait for accept cookies button to appear
-# accept_cookies_button = WebDriverWait(driver, 10).until(
-# EC.presence_of_element_located(
-# (By.XPATH, '/html/body/div[4]/div/div[2]/div/div/div[3]/div/div[1]/button[1]/div/div')
-# )
-# )
-# accept_cookies_button.click()
-
-# # Wait for banner to disappear
-# time.sleep(1)
-
-# # Process the HTML file
-# dom_service = DomService(driver)
-# result = dom_service.get_clickable_elements()
-
-# # Add assertions based on expected content of page.html
-# print(f'Processed DOM content: {result.output_html}')
-# # print(f'Selector map: {result.selector_map}')
-
-# print('Tokens:', count_string_tokens(result.output_html, 'gpt-4o'))
diff --git a/src/dom/views.py b/src/dom/views.py
index ae47318e2..9933c381d 100644
--- a/src/dom/views.py
+++ b/src/dom/views.py
@@ -4,6 +4,7 @@ from pydantic import BaseModel
class DomContentItem(BaseModel):
index: int
text: str
+ clickable: bool
class ProcessedDomContent(BaseModel):
@@ -12,4 +13,10 @@ class ProcessedDomContent(BaseModel):
def dom_items_to_string(self) -> str:
"""Convert the processed DOM content to HTML."""
- return '\n'.join([f'{item.index}:{item.text}' for item in self.items])
+ formatted_text = ''
+ for item in self.items:
+ if item.clickable:
+ formatted_text += f'{item.index}:{item.text}\n'
+ else:
+ formatted_text += f'_:{item.text}\n'
+ return formatted_text