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
added shadow dom support
Gregor Žunič03d30a81ff31
diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.pyindex bd328f012..67d949bb3 100644--- a/browser_use/dom/playground/extraction.py+++ b/browser_use/dom/playground/extraction.py@@ -32,6 +32,7 @@ async def test_focus_vs_all_elements():# 10 Sample websites with various interactive elementssample_websites = [+ 'https://v0-website-with-clickable-elements.vercel.app/shadow-dom','https://www.google.com/travel/flights','https://www.amazon.com/s?k=laptop','https://github.com/trending',@@ -170,9 +171,12 @@ async def test_focus_vs_all_elements():# save pure clickable elements to a fileif all_elements_state.dom_state._root:- async with await anyio.open_file('./tmp/element_tree.json', 'w', encoding='utf-8') as f:+ async with await anyio.open_file('./tmp/simplified_element_tree.json', 'w', encoding='utf-8') as f:await f.write(json.dumps(all_elements_state.dom_state._root.__json__(), indent=2))+ async with await anyio.open_file('./tmp/original_element_tree.json', 'w', encoding='utf-8') as f:+ await f.write(json.dumps(all_elements_state.dom_state._root.original_node.__json__(), indent=2))+# copy the user message to the clipboard# pyperclip.copy(text_to_save)@@ -181,7 +185,8 @@ async def test_focus_vs_all_elements():print(f'Token count: {token_count}')print('User message written to ./tmp/user_message.txt')- print('Element tree written to ./tmp/element_tree.json')+ print('Element tree written to ./tmp/simplified_element_tree.json')+ print('Original element tree written to ./tmp/original_element_tree.json')# Save timing informationtiming_text = '🔍 DOM EXTRACTION PERFORMANCE ANALYSIS\n'@@ -226,7 +231,7 @@ async def test_focus_vs_all_elements():website_list = get_website_list_for_prompt()answer = input(- f"\n{website_list}\n\n🎮 Enter: element index | 'index,text' input | 'c,index' copy | 1-15 jump | Enter re-run | 'n' next | 'q' quit: "+ "🎮 Enter: element index | 'index' click (clickable) | 'index,text' input | 'c,index' copy | Enter re-run | 'n' next | 'q' quit: ")if answer.lower() == 'q':@@ -239,19 +244,16 @@ async def test_focus_vs_all_elements():print('Re-running extraction on current page state...')continue # Continue inner loop to re-extract DOM without reloading pageelif answer.strip().isdigit():- # Jump to specific website (1-15)+ # Click element format: indextry:- target_website = int(answer.strip())- if 1 <= target_website <= len(websites):- current_website_index = target_website - 1 # Convert to 0-based index- target_url = websites[current_website_index]- website_type = 'DIFFICULT' if target_url in difficult_websites else 'SAMPLE'- print(f'Jumping to website {target_website}: [{website_type}] {target_url}')- break # Break inner loop to go to new website- else:- print(f'Invalid website number. Enter 1-{len(websites)}.')+ clicked_index = int(answer)+ if clicked_index in selector_map:+ element_node = selector_map[clicked_index]+ print(f'Clicking element {clicked_index}: {element_node.tag_name}')+ await browser_session._click_element_node(element_node)+ print('Click successful.')except ValueError:- print(f'Invalid input: {answer}')+ print(f"Invalid input: '{answer}'. Enter an index, 'index,text', 'c,index', or 'q'.")continuetry:@@ -292,19 +294,6 @@ async def test_focus_vs_all_elements():print(f'Invalid index format: {parts[0]}')else:print("Invalid input format. Use 'index,text'.")- else:- # Click element format: index- try:- clicked_index = int(answer)- if clicked_index in selector_map:- element_node = selector_map[clicked_index]- print(f'Clicking element {clicked_index}: {element_node.tag_name}')- await browser_session._click_element_node(element_node)- print('Click successful.')- else:- print(f'Invalid index: {clicked_index}')- except ValueError:- print(f"Invalid input: '{answer}'. Enter an index, 'index,text', 'c,index', or 'q'.")except Exception as action_e:print(f'Action failed: {action_e}')diff --git a/browser_use/dom/serializer/serializer.py b/browser_use/dom/serializer/serializer.pyindex e13e982a1..eed74af99 100644--- a/browser_use/dom/serializer/serializer.py+++ b/browser_use/dom/serializer/serializer.py@@ -5,6 +5,8 @@ from browser_use.dom.serializer.clickable_elements import ClickableElementDetectfrom browser_use.dom.utils import cap_text_lengthfrom browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, NodeType, SerializedDOMState, SimplifiedNode+DISABLED_ELEMENTS = {'style', 'script', 'head', 'meta', 'link', 'title'}+class DOMTreeSerializer:"""Serializes enhanced DOM trees to string format."""@@ -78,24 +80,26 @@ class DOMTreeSerializer:"""Step 1: Create a simplified tree with enhanced element detection."""if node.node_type == NodeType.DOCUMENT_NODE:- if node.children_nodes:- for child in node.children_nodes:- simplified_child = self._create_simplified_tree(child)- if simplified_child:- return simplified_child+ # for all children including shadow roots+ for child in node.children_and_shadow_roots:+ simplified_child = self._create_simplified_tree(child)+ if simplified_child:+ return simplified_child+return None- elif node.node_type == NodeType.ELEMENT_NODE:- if node.node_name == '#document':- if node.children_nodes:- for child in node.children_nodes:- simplified_child = self._create_simplified_tree(child)- if simplified_child:- return simplified_child- return None+ if node.node_type == NodeType.DOCUMENT_FRAGMENT_NODE:+ # Super simple pass-through for shadow DOM elements+ simplified = SimplifiedNode(original_node=node, children=[])+ for child in node.children_and_shadow_roots:+ simplified_child = self._create_simplified_tree(child)+ if simplified_child:+ simplified.children.append(simplified_child)+ return simplified+ elif node.node_type == NodeType.ELEMENT_NODE:# Skip non-content elements- if node.node_name.lower() in ['style', 'script', 'head', 'meta', 'link', 'title']:+ if node.node_name.lower() in DISABLED_ELEMENTS:return None# Use enhanced scoring for inclusion decision@@ -105,18 +109,17 @@ class DOMTreeSerializer:is_scrollable = node.is_scrollable# Include if interactive (regardless of visibility), or scrollable, or has children to process- should_include = (is_interactive and is_visible) or is_scrollable or node.children_nodes+ should_include = (is_interactive and is_visible) or is_scrollable or node.children_and_shadow_rootsif should_include:- simplified = SimplifiedNode(original_node=node)+ simplified = SimplifiedNode(original_node=node, children=[])# simplified._analysis = analysis # Store analysis for grouping# Process children- if node.children_nodes:- for child in node.children_nodes:- simplified_child = self._create_simplified_tree(child)- if simplified_child:- simplified.children.append(simplified_child)+ for child in node.children_and_shadow_roots:+ simplified_child = self._create_simplified_tree(child)+ if simplified_child:+ simplified.children.append(simplified_child)# Return if meaningful or has meaningful childrenif (is_interactive and is_visible) or is_scrollable or simplified.children:@@ -126,7 +129,7 @@ class DOMTreeSerializer:# Include meaningful text nodesis_visible = node.snapshot_node and node.snapshot_node.is_visibleif is_visible and node.node_value and node.node_value.strip() and len(node.node_value.strip()) > 1:- return SimplifiedNode(original_node=node)+ return SimplifiedNode(original_node=node, children=[])return Nonediff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 4a99b01a3..74d32706c 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -1,5 +1,5 @@import hashlib-from dataclasses import asdict, dataclass, field+from dataclasses import asdict, dataclassfrom enum import Enumfrom typing import Any@@ -31,17 +31,20 @@ class SimplifiedNode:"""Simplified tree node for optimization."""original_node: 'EnhancedDOMTreeNode'- children: list['SimplifiedNode'] = field(default_factory=list)+ children: list['SimplifiedNode']should_display: bool = Trueinteractive_index: int | None = Noneis_new: bool = Falsedef __json__(self) -> dict:+ original_node_json = self.original_node.__json__()+ del original_node_json['children_nodes']+ del original_node_json['shadow_roots']return {'should_display': self.should_display,'interactive_index': self.interactive_index,- 'original_node': self.original_node.__json__(),+ 'original_node': original_node_json,'children': [c.__json__() for c in self.children],}@@ -192,6 +195,16 @@ class EnhancedDOMTreeNode:def children(self) -> list['EnhancedDOMTreeNode']:return self.children_nodes or []+ @property+ def children_and_shadow_roots(self) -> list['EnhancedDOMTreeNode']:+ """+ Returns all children nodes, including shadow roots+ """+ children = self.children_nodes or []+ if self.shadow_roots:+ children.extend(self.shadow_roots)+ return children+@propertydef tag_name(self) -> str:return self.node_name.lower()