optexity-browser-use 0.9.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. browser_use/__init__.py +157 -0
  2. browser_use/actor/__init__.py +11 -0
  3. browser_use/actor/element.py +1175 -0
  4. browser_use/actor/mouse.py +134 -0
  5. browser_use/actor/page.py +561 -0
  6. browser_use/actor/playground/flights.py +41 -0
  7. browser_use/actor/playground/mixed_automation.py +54 -0
  8. browser_use/actor/playground/playground.py +236 -0
  9. browser_use/actor/utils.py +176 -0
  10. browser_use/agent/cloud_events.py +282 -0
  11. browser_use/agent/gif.py +424 -0
  12. browser_use/agent/judge.py +170 -0
  13. browser_use/agent/message_manager/service.py +473 -0
  14. browser_use/agent/message_manager/utils.py +52 -0
  15. browser_use/agent/message_manager/views.py +98 -0
  16. browser_use/agent/prompts.py +413 -0
  17. browser_use/agent/service.py +2316 -0
  18. browser_use/agent/system_prompt.md +185 -0
  19. browser_use/agent/system_prompt_flash.md +10 -0
  20. browser_use/agent/system_prompt_no_thinking.md +183 -0
  21. browser_use/agent/views.py +743 -0
  22. browser_use/browser/__init__.py +41 -0
  23. browser_use/browser/cloud/cloud.py +203 -0
  24. browser_use/browser/cloud/views.py +89 -0
  25. browser_use/browser/events.py +578 -0
  26. browser_use/browser/profile.py +1158 -0
  27. browser_use/browser/python_highlights.py +548 -0
  28. browser_use/browser/session.py +3225 -0
  29. browser_use/browser/session_manager.py +399 -0
  30. browser_use/browser/video_recorder.py +162 -0
  31. browser_use/browser/views.py +200 -0
  32. browser_use/browser/watchdog_base.py +260 -0
  33. browser_use/browser/watchdogs/__init__.py +0 -0
  34. browser_use/browser/watchdogs/aboutblank_watchdog.py +253 -0
  35. browser_use/browser/watchdogs/crash_watchdog.py +335 -0
  36. browser_use/browser/watchdogs/default_action_watchdog.py +2729 -0
  37. browser_use/browser/watchdogs/dom_watchdog.py +817 -0
  38. browser_use/browser/watchdogs/downloads_watchdog.py +1277 -0
  39. browser_use/browser/watchdogs/local_browser_watchdog.py +461 -0
  40. browser_use/browser/watchdogs/permissions_watchdog.py +43 -0
  41. browser_use/browser/watchdogs/popups_watchdog.py +143 -0
  42. browser_use/browser/watchdogs/recording_watchdog.py +126 -0
  43. browser_use/browser/watchdogs/screenshot_watchdog.py +62 -0
  44. browser_use/browser/watchdogs/security_watchdog.py +280 -0
  45. browser_use/browser/watchdogs/storage_state_watchdog.py +335 -0
  46. browser_use/cli.py +2359 -0
  47. browser_use/code_use/__init__.py +16 -0
  48. browser_use/code_use/formatting.py +192 -0
  49. browser_use/code_use/namespace.py +665 -0
  50. browser_use/code_use/notebook_export.py +276 -0
  51. browser_use/code_use/service.py +1340 -0
  52. browser_use/code_use/system_prompt.md +574 -0
  53. browser_use/code_use/utils.py +150 -0
  54. browser_use/code_use/views.py +171 -0
  55. browser_use/config.py +505 -0
  56. browser_use/controller/__init__.py +3 -0
  57. browser_use/dom/enhanced_snapshot.py +161 -0
  58. browser_use/dom/markdown_extractor.py +169 -0
  59. browser_use/dom/playground/extraction.py +312 -0
  60. browser_use/dom/playground/multi_act.py +32 -0
  61. browser_use/dom/serializer/clickable_elements.py +200 -0
  62. browser_use/dom/serializer/code_use_serializer.py +287 -0
  63. browser_use/dom/serializer/eval_serializer.py +478 -0
  64. browser_use/dom/serializer/html_serializer.py +212 -0
  65. browser_use/dom/serializer/paint_order.py +197 -0
  66. browser_use/dom/serializer/serializer.py +1170 -0
  67. browser_use/dom/service.py +825 -0
  68. browser_use/dom/utils.py +129 -0
  69. browser_use/dom/views.py +906 -0
  70. browser_use/exceptions.py +5 -0
  71. browser_use/filesystem/__init__.py +0 -0
  72. browser_use/filesystem/file_system.py +619 -0
  73. browser_use/init_cmd.py +376 -0
  74. browser_use/integrations/gmail/__init__.py +24 -0
  75. browser_use/integrations/gmail/actions.py +115 -0
  76. browser_use/integrations/gmail/service.py +225 -0
  77. browser_use/llm/__init__.py +155 -0
  78. browser_use/llm/anthropic/chat.py +242 -0
  79. browser_use/llm/anthropic/serializer.py +312 -0
  80. browser_use/llm/aws/__init__.py +36 -0
  81. browser_use/llm/aws/chat_anthropic.py +242 -0
  82. browser_use/llm/aws/chat_bedrock.py +289 -0
  83. browser_use/llm/aws/serializer.py +257 -0
  84. browser_use/llm/azure/chat.py +91 -0
  85. browser_use/llm/base.py +57 -0
  86. browser_use/llm/browser_use/__init__.py +3 -0
  87. browser_use/llm/browser_use/chat.py +201 -0
  88. browser_use/llm/cerebras/chat.py +193 -0
  89. browser_use/llm/cerebras/serializer.py +109 -0
  90. browser_use/llm/deepseek/chat.py +212 -0
  91. browser_use/llm/deepseek/serializer.py +109 -0
  92. browser_use/llm/exceptions.py +29 -0
  93. browser_use/llm/google/__init__.py +3 -0
  94. browser_use/llm/google/chat.py +542 -0
  95. browser_use/llm/google/serializer.py +120 -0
  96. browser_use/llm/groq/chat.py +229 -0
  97. browser_use/llm/groq/parser.py +158 -0
  98. browser_use/llm/groq/serializer.py +159 -0
  99. browser_use/llm/messages.py +238 -0
  100. browser_use/llm/models.py +271 -0
  101. browser_use/llm/oci_raw/__init__.py +10 -0
  102. browser_use/llm/oci_raw/chat.py +443 -0
  103. browser_use/llm/oci_raw/serializer.py +229 -0
  104. browser_use/llm/ollama/chat.py +97 -0
  105. browser_use/llm/ollama/serializer.py +143 -0
  106. browser_use/llm/openai/chat.py +264 -0
  107. browser_use/llm/openai/like.py +15 -0
  108. browser_use/llm/openai/serializer.py +165 -0
  109. browser_use/llm/openrouter/chat.py +211 -0
  110. browser_use/llm/openrouter/serializer.py +26 -0
  111. browser_use/llm/schema.py +176 -0
  112. browser_use/llm/views.py +48 -0
  113. browser_use/logging_config.py +330 -0
  114. browser_use/mcp/__init__.py +18 -0
  115. browser_use/mcp/__main__.py +12 -0
  116. browser_use/mcp/client.py +544 -0
  117. browser_use/mcp/controller.py +264 -0
  118. browser_use/mcp/server.py +1114 -0
  119. browser_use/observability.py +204 -0
  120. browser_use/py.typed +0 -0
  121. browser_use/sandbox/__init__.py +41 -0
  122. browser_use/sandbox/sandbox.py +637 -0
  123. browser_use/sandbox/views.py +132 -0
  124. browser_use/screenshots/__init__.py +1 -0
  125. browser_use/screenshots/service.py +52 -0
  126. browser_use/sync/__init__.py +6 -0
  127. browser_use/sync/auth.py +357 -0
  128. browser_use/sync/service.py +161 -0
  129. browser_use/telemetry/__init__.py +51 -0
  130. browser_use/telemetry/service.py +112 -0
  131. browser_use/telemetry/views.py +101 -0
  132. browser_use/tokens/__init__.py +0 -0
  133. browser_use/tokens/custom_pricing.py +24 -0
  134. browser_use/tokens/mappings.py +4 -0
  135. browser_use/tokens/service.py +580 -0
  136. browser_use/tokens/views.py +108 -0
  137. browser_use/tools/registry/service.py +572 -0
  138. browser_use/tools/registry/views.py +174 -0
  139. browser_use/tools/service.py +1675 -0
  140. browser_use/tools/utils.py +82 -0
  141. browser_use/tools/views.py +100 -0
  142. browser_use/utils.py +670 -0
  143. optexity_browser_use-0.9.5.dist-info/METADATA +344 -0
  144. optexity_browser_use-0.9.5.dist-info/RECORD +147 -0
  145. optexity_browser_use-0.9.5.dist-info/WHEEL +4 -0
  146. optexity_browser_use-0.9.5.dist-info/entry_points.txt +3 -0
  147. optexity_browser_use-0.9.5.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,478 @@
1
+ # @file purpose: Concise evaluation serializer for DOM trees - optimized for LLM query writing
2
+
3
+
4
+ from browser_use.dom.utils import cap_text_length
5
+ from browser_use.dom.views import (
6
+ EnhancedDOMTreeNode,
7
+ NodeType,
8
+ SimplifiedNode,
9
+ )
10
+
11
+ # Critical attributes for query writing and form interaction
12
+ # NOTE: Removed 'id' and 'class' to force more robust structural selectors
13
+ EVAL_KEY_ATTRIBUTES = [
14
+ 'id', # Removed - can have special chars, forces structural selectors
15
+ 'class', # Removed - can have special chars like +, forces structural selectors
16
+ 'name',
17
+ 'type',
18
+ 'placeholder',
19
+ 'aria-label',
20
+ 'role',
21
+ 'value',
22
+ # 'href',
23
+ 'data-testid',
24
+ 'alt', # for images
25
+ 'title', # useful for tooltips/link context
26
+ # State attributes (critical for form interaction)
27
+ 'checked',
28
+ 'selected',
29
+ 'disabled',
30
+ 'required',
31
+ 'readonly',
32
+ # ARIA states
33
+ 'aria-expanded',
34
+ 'aria-pressed',
35
+ 'aria-checked',
36
+ 'aria-selected',
37
+ 'aria-invalid',
38
+ # Validation attributes (help agents avoid brute force)
39
+ 'pattern',
40
+ 'min',
41
+ 'max',
42
+ 'minlength',
43
+ 'maxlength',
44
+ 'step',
45
+ 'aria-valuemin',
46
+ 'aria-valuemax',
47
+ 'aria-valuenow',
48
+ ]
49
+
50
+ # Semantic elements that should always be shown
51
+ SEMANTIC_ELEMENTS = {
52
+ 'html', # Always show document root
53
+ 'body', # Always show body
54
+ 'h1',
55
+ 'h2',
56
+ 'h3',
57
+ 'h4',
58
+ 'h5',
59
+ 'h6',
60
+ 'a',
61
+ 'button',
62
+ 'input',
63
+ 'textarea',
64
+ 'select',
65
+ 'form',
66
+ 'label',
67
+ 'nav',
68
+ 'header',
69
+ 'footer',
70
+ 'main',
71
+ 'article',
72
+ 'section',
73
+ 'table',
74
+ 'thead',
75
+ 'tbody',
76
+ 'tr',
77
+ 'th',
78
+ 'td',
79
+ 'ul',
80
+ 'ol',
81
+ 'li',
82
+ 'img',
83
+ 'iframe',
84
+ 'video',
85
+ 'audio',
86
+ }
87
+
88
+ # Container elements that can be collapsed if they only wrap one child
89
+ COLLAPSIBLE_CONTAINERS = {'div', 'span', 'section', 'article'}
90
+
91
+ # SVG child elements to skip (decorative only, no interaction value)
92
+ SVG_ELEMENTS = {
93
+ 'path',
94
+ 'rect',
95
+ 'g',
96
+ 'circle',
97
+ 'ellipse',
98
+ 'line',
99
+ 'polyline',
100
+ 'polygon',
101
+ 'use',
102
+ 'defs',
103
+ 'clipPath',
104
+ 'mask',
105
+ 'pattern',
106
+ 'image',
107
+ 'text',
108
+ 'tspan',
109
+ }
110
+
111
+
112
+ class DOMEvalSerializer:
113
+ """Ultra-concise DOM serializer for quick LLM query writing."""
114
+
115
+ @staticmethod
116
+ def serialize_tree(node: SimplifiedNode | None, include_attributes: list[str], depth: int = 0) -> str:
117
+ """
118
+ Serialize complete DOM tree structure for LLM understanding.
119
+
120
+ Strategy:
121
+ - Show ALL elements to preserve DOM structure
122
+ - Non-interactive elements show just tag name
123
+ - Interactive elements show full attributes + [index]
124
+ - Self-closing tags only (no closing tags)
125
+ """
126
+ if not node:
127
+ return ''
128
+
129
+ # Skip excluded nodes but process children
130
+ if hasattr(node, 'excluded_by_parent') and node.excluded_by_parent:
131
+ return DOMEvalSerializer._serialize_children(node, include_attributes, depth)
132
+
133
+ # Skip nodes marked as should_display=False
134
+ if not node.should_display:
135
+ return DOMEvalSerializer._serialize_children(node, include_attributes, depth)
136
+
137
+ formatted_text = []
138
+ depth_str = depth * '\t'
139
+
140
+ if node.original_node.node_type == NodeType.ELEMENT_NODE:
141
+ tag = node.original_node.tag_name.lower()
142
+ is_visible = node.original_node.snapshot_node and node.original_node.is_visible
143
+
144
+ # Container elements that should be shown even if invisible (might have visible children)
145
+ container_tags = {'html', 'body', 'div', 'main', 'section', 'article', 'aside', 'header', 'footer', 'nav'}
146
+
147
+ # Skip invisible elements UNLESS they're containers or iframes (which might have visible children)
148
+ if not is_visible and tag not in container_tags and tag not in ['iframe', 'frame']:
149
+ return DOMEvalSerializer._serialize_children(node, include_attributes, depth)
150
+
151
+ # Special handling for iframes - show them with their content
152
+ if tag in ['iframe', 'frame']:
153
+ return DOMEvalSerializer._serialize_iframe(node, include_attributes, depth)
154
+
155
+ # Skip SVG elements entirely - they're just decorative graphics with no interaction value
156
+ # Show the <svg> tag itself to indicate graphics, but don't recurse into children
157
+ if tag == 'svg':
158
+ line = f'{depth_str}'
159
+ # Add [i_X] for interactive SVG elements only
160
+ if node.is_interactive:
161
+ line += f'[i_{node.original_node.backend_node_id}] '
162
+ line += '<svg'
163
+ attributes_str = DOMEvalSerializer._build_compact_attributes(node.original_node)
164
+ if attributes_str:
165
+ line += f' {attributes_str}'
166
+ line += ' /> <!-- SVG content collapsed -->'
167
+ return line
168
+
169
+ # Skip SVG child elements entirely (path, rect, g, circle, etc.)
170
+ if tag in SVG_ELEMENTS:
171
+ return ''
172
+
173
+ # Build compact attributes string
174
+ attributes_str = DOMEvalSerializer._build_compact_attributes(node.original_node)
175
+
176
+ # Decide if this element should be shown
177
+ is_semantic = tag in SEMANTIC_ELEMENTS
178
+ has_useful_attrs = bool(attributes_str)
179
+ has_text_content = DOMEvalSerializer._has_direct_text(node)
180
+ has_children = len(node.children) > 0
181
+
182
+ # Build compact element representation
183
+ line = f'{depth_str}'
184
+ # Add backend node ID notation - [i_X] for interactive elements only
185
+ if node.is_interactive:
186
+ line += f'[i_{node.original_node.backend_node_id}] '
187
+ # Non-interactive elements don't get an index notation
188
+ line += f'<{tag}'
189
+
190
+ if attributes_str:
191
+ line += f' {attributes_str}'
192
+
193
+ # Add scroll info if element is scrollable
194
+ if node.original_node.should_show_scroll_info:
195
+ scroll_text = node.original_node.get_scroll_info_text()
196
+ if scroll_text:
197
+ line += f' scroll="{scroll_text}"'
198
+
199
+ # Add inline text if present (keep it on same line for compactness)
200
+ inline_text = DOMEvalSerializer._get_inline_text(node)
201
+
202
+ # For containers (html, body, div, etc.), always show children even if there's inline text
203
+ # For other elements, inline text replaces children (more compact)
204
+ is_container = tag in container_tags
205
+
206
+ if inline_text and not is_container:
207
+ line += f'>{inline_text}'
208
+ else:
209
+ line += ' />'
210
+
211
+ formatted_text.append(line)
212
+
213
+ # Process children (always for containers, only if no inline_text for others)
214
+ if has_children and (is_container or not inline_text):
215
+ children_text = DOMEvalSerializer._serialize_children(node, include_attributes, depth + 1)
216
+ if children_text:
217
+ formatted_text.append(children_text)
218
+
219
+ elif node.original_node.node_type == NodeType.TEXT_NODE:
220
+ # Text nodes are handled inline with their parent
221
+ pass
222
+
223
+ elif node.original_node.node_type == NodeType.DOCUMENT_FRAGMENT_NODE:
224
+ # Shadow DOM - just show children directly with minimal marker
225
+ if node.children:
226
+ formatted_text.append(f'{depth_str}#shadow')
227
+ children_text = DOMEvalSerializer._serialize_children(node, include_attributes, depth + 1)
228
+ if children_text:
229
+ formatted_text.append(children_text)
230
+
231
+ return '\n'.join(formatted_text)
232
+
233
+ @staticmethod
234
+ def _serialize_children(node: SimplifiedNode, include_attributes: list[str], depth: int) -> str:
235
+ """Helper to serialize all children of a node."""
236
+ children_output = []
237
+
238
+ # Check if parent is a list container (ul, ol)
239
+ is_list_container = node.original_node.node_type == NodeType.ELEMENT_NODE and node.original_node.tag_name.lower() in [
240
+ 'ul',
241
+ 'ol',
242
+ ]
243
+
244
+ # Track list items and consecutive links
245
+ li_count = 0
246
+ max_list_items = 50
247
+ consecutive_link_count = 0
248
+ max_consecutive_links = 50
249
+ total_links_skipped = 0
250
+
251
+ for child in node.children:
252
+ # Get tag name for this child
253
+ current_tag = None
254
+ if child.original_node.node_type == NodeType.ELEMENT_NODE:
255
+ current_tag = child.original_node.tag_name.lower()
256
+
257
+ # If we're in a list container and this child is an li element
258
+ if is_list_container and current_tag == 'li':
259
+ li_count += 1
260
+ # Skip li elements after the 5th one
261
+ if li_count > max_list_items:
262
+ continue
263
+
264
+ # Track consecutive anchor tags (links)
265
+ if current_tag == 'a':
266
+ consecutive_link_count += 1
267
+ # Skip links after the 5th consecutive one
268
+ if consecutive_link_count > max_consecutive_links:
269
+ total_links_skipped += 1
270
+ continue
271
+ else:
272
+ # Reset counter when we hit a non-link element
273
+ # But first add truncation message if we skipped links
274
+ if total_links_skipped > 0:
275
+ depth_str = depth * '\t'
276
+ children_output.append(f'{depth_str}... ({total_links_skipped} more links in this list)')
277
+ total_links_skipped = 0
278
+ consecutive_link_count = 0
279
+
280
+ child_text = DOMEvalSerializer.serialize_tree(child, include_attributes, depth)
281
+ if child_text:
282
+ children_output.append(child_text)
283
+
284
+ # Add truncation message if we skipped items at the end
285
+ if is_list_container and li_count > max_list_items:
286
+ depth_str = depth * '\t'
287
+ children_output.append(
288
+ f'{depth_str}... ({li_count - max_list_items} more items in this list (truncated) use evaluate to get more.'
289
+ )
290
+
291
+ # Add truncation message for links if we skipped any at the end
292
+ if total_links_skipped > 0:
293
+ depth_str = depth * '\t'
294
+ children_output.append(
295
+ f'{depth_str}... ({total_links_skipped} more links in this list) (truncated) use evaluate to get more.'
296
+ )
297
+
298
+ return '\n'.join(children_output)
299
+
300
+ @staticmethod
301
+ def _build_compact_attributes(node: EnhancedDOMTreeNode) -> str:
302
+ """Build ultra-compact attributes string with only key attributes."""
303
+ attrs = []
304
+
305
+ # Prioritize attributes that help with query writing
306
+ if node.attributes:
307
+ for attr in EVAL_KEY_ATTRIBUTES:
308
+ if attr in node.attributes:
309
+ value = str(node.attributes[attr]).strip()
310
+ if not value:
311
+ continue
312
+
313
+ # Special handling for different attributes
314
+ if attr == 'class':
315
+ # For class, limit to first 2 classes to save space
316
+ classes = value.split()[:3]
317
+ value = ' '.join(classes)
318
+ elif attr == 'href':
319
+ # For href, cap at 20 chars to save space
320
+ value = cap_text_length(value, 80)
321
+ else:
322
+ # Cap at 25 chars for other attributes
323
+ value = cap_text_length(value, 80)
324
+
325
+ attrs.append(f'{attr}="{value}"')
326
+
327
+ # Note: We intentionally don't add role from ax_node here because:
328
+ # 1. If role is explicitly set in HTML, it's already captured above via EVAL_KEY_ATTRIBUTES
329
+ # 2. Inferred roles from AX tree (like link, listitem, LineBreak) are redundant with the tag name
330
+ # 3. This reduces noise - <a href="..." role="link"> is redundant, we already know <a> is a link
331
+
332
+ return ' '.join(attrs)
333
+
334
+ @staticmethod
335
+ def _has_direct_text(node: SimplifiedNode) -> bool:
336
+ """Check if node has direct text children (not nested in other elements)."""
337
+ for child in node.children:
338
+ if child.original_node.node_type == NodeType.TEXT_NODE:
339
+ text = child.original_node.node_value.strip() if child.original_node.node_value else ''
340
+ if len(text) > 1:
341
+ return True
342
+ return False
343
+
344
+ @staticmethod
345
+ def _get_inline_text(node: SimplifiedNode) -> str:
346
+ """Get text content to display inline (max 40 chars)."""
347
+ text_parts = []
348
+ for child in node.children:
349
+ if child.original_node.node_type == NodeType.TEXT_NODE:
350
+ text = child.original_node.node_value.strip() if child.original_node.node_value else ''
351
+ if text and len(text) > 1:
352
+ text_parts.append(text)
353
+
354
+ if not text_parts:
355
+ return ''
356
+
357
+ combined = ' '.join(text_parts)
358
+ return cap_text_length(combined, 80)
359
+
360
+ @staticmethod
361
+ def _serialize_iframe(node: SimplifiedNode, include_attributes: list[str], depth: int) -> str:
362
+ """Handle iframe serialization with content document."""
363
+ formatted_text = []
364
+ depth_str = depth * '\t'
365
+ tag = node.original_node.tag_name.lower()
366
+
367
+ # Build minimal iframe marker with key attributes
368
+ attributes_str = DOMEvalSerializer._build_compact_attributes(node.original_node)
369
+ line = f'{depth_str}<{tag}'
370
+ if attributes_str:
371
+ line += f' {attributes_str}'
372
+
373
+ # Add scroll info for iframe content
374
+ if node.original_node.should_show_scroll_info:
375
+ scroll_text = node.original_node.get_scroll_info_text()
376
+ if scroll_text:
377
+ line += f' scroll="{scroll_text}"'
378
+
379
+ line += ' />'
380
+ formatted_text.append(line)
381
+
382
+ # If iframe has content document, serialize its content
383
+ if node.original_node.content_document:
384
+ # Add marker for iframe content
385
+ formatted_text.append(f'{depth_str}\t#iframe-content')
386
+
387
+ # Process content document children
388
+ for child_node in node.original_node.content_document.children_nodes or []:
389
+ # Process html documents
390
+ if child_node.tag_name.lower() == 'html':
391
+ # Find and serialize body content only (skip head)
392
+ for html_child in child_node.children:
393
+ if html_child.tag_name.lower() == 'body':
394
+ for body_child in html_child.children:
395
+ # Recursively process body children (iframe content)
396
+ DOMEvalSerializer._serialize_document_node(
397
+ body_child, formatted_text, include_attributes, depth + 2, is_iframe_content=True
398
+ )
399
+ break # Stop after processing body
400
+ else:
401
+ # Not an html element - serialize directly
402
+ DOMEvalSerializer._serialize_document_node(
403
+ child_node, formatted_text, include_attributes, depth + 1, is_iframe_content=True
404
+ )
405
+
406
+ return '\n'.join(formatted_text)
407
+
408
+ @staticmethod
409
+ def _serialize_document_node(
410
+ dom_node: EnhancedDOMTreeNode,
411
+ output: list[str],
412
+ include_attributes: list[str],
413
+ depth: int,
414
+ is_iframe_content: bool = True,
415
+ ) -> None:
416
+ """Helper to serialize a document node without SimplifiedNode wrapper.
417
+
418
+ Args:
419
+ is_iframe_content: If True, be more permissive with visibility checks since
420
+ iframe content might not have snapshot data from parent page.
421
+ """
422
+ depth_str = depth * '\t'
423
+
424
+ if dom_node.node_type == NodeType.ELEMENT_NODE:
425
+ tag = dom_node.tag_name.lower()
426
+
427
+ # For iframe content, be permissive - show all semantic elements even without snapshot data
428
+ # For regular content, skip invisible elements
429
+ if is_iframe_content:
430
+ # Only skip if we have snapshot data AND it's explicitly invisible
431
+ # If no snapshot data, assume visible (cross-origin iframe content)
432
+ is_visible = (not dom_node.snapshot_node) or dom_node.is_visible
433
+ else:
434
+ # Regular strict visibility check
435
+ is_visible = dom_node.snapshot_node and dom_node.is_visible
436
+
437
+ if not is_visible:
438
+ return
439
+
440
+ # Check if semantic or has useful attributes
441
+ is_semantic = tag in SEMANTIC_ELEMENTS
442
+ attributes_str = DOMEvalSerializer._build_compact_attributes(dom_node)
443
+
444
+ if not is_semantic and not attributes_str:
445
+ # Skip but process children
446
+ for child in dom_node.children:
447
+ DOMEvalSerializer._serialize_document_node(
448
+ child, output, include_attributes, depth, is_iframe_content=is_iframe_content
449
+ )
450
+ return
451
+
452
+ # Build element line
453
+ line = f'{depth_str}<{tag}'
454
+ if attributes_str:
455
+ line += f' {attributes_str}'
456
+
457
+ # Get direct text content
458
+ text_parts = []
459
+ for child in dom_node.children:
460
+ if child.node_type == NodeType.TEXT_NODE and child.node_value:
461
+ text = child.node_value.strip()
462
+ if text and len(text) > 1:
463
+ text_parts.append(text)
464
+
465
+ if text_parts:
466
+ combined = ' '.join(text_parts)
467
+ line += f'>{cap_text_length(combined, 100)}'
468
+ else:
469
+ line += ' />'
470
+
471
+ output.append(line)
472
+
473
+ # Process non-text children
474
+ for child in dom_node.children:
475
+ if child.node_type != NodeType.TEXT_NODE:
476
+ DOMEvalSerializer._serialize_document_node(
477
+ child, output, include_attributes, depth + 1, is_iframe_content=is_iframe_content
478
+ )
@@ -0,0 +1,212 @@
1
+ # @file purpose: Serializes enhanced DOM trees to HTML format including shadow roots
2
+
3
+ from browser_use.dom.views import EnhancedDOMTreeNode, NodeType
4
+
5
+
6
+ class HTMLSerializer:
7
+ """Serializes enhanced DOM trees back to HTML format.
8
+
9
+ This serializer reconstructs HTML from the enhanced DOM tree, including:
10
+ - Shadow DOM content (both open and closed)
11
+ - Iframe content documents
12
+ - All attributes and text nodes
13
+ - Proper HTML structure
14
+
15
+ Unlike getOuterHTML which only captures light DOM, this captures the full
16
+ enhanced tree including shadow roots that are crucial for modern SPAs.
17
+ """
18
+
19
+ def __init__(self, extract_links: bool = False):
20
+ """Initialize the HTML serializer.
21
+
22
+ Args:
23
+ extract_links: If True, preserves all links. If False, removes href attributes.
24
+ """
25
+ self.extract_links = extract_links
26
+
27
+ def serialize(self, node: EnhancedDOMTreeNode, depth: int = 0) -> str:
28
+ """Serialize an enhanced DOM tree node to HTML.
29
+
30
+ Args:
31
+ node: The enhanced DOM tree node to serialize
32
+ depth: Current depth for indentation (internal use)
33
+
34
+ Returns:
35
+ HTML string representation of the node and its descendants
36
+ """
37
+ if node.node_type == NodeType.DOCUMENT_NODE:
38
+ # Process document root - serialize all children
39
+ parts = []
40
+ for child in node.children_and_shadow_roots:
41
+ child_html = self.serialize(child, depth)
42
+ if child_html:
43
+ parts.append(child_html)
44
+ return ''.join(parts)
45
+
46
+ elif node.node_type == NodeType.DOCUMENT_FRAGMENT_NODE:
47
+ # Shadow DOM root - wrap in template with shadowrootmode attribute
48
+ parts = []
49
+
50
+ # Add shadow root opening
51
+ shadow_type = node.shadow_root_type or 'open'
52
+ parts.append(f'<template shadowroot="{shadow_type.lower()}">')
53
+
54
+ # Serialize shadow children
55
+ for child in node.children:
56
+ child_html = self.serialize(child, depth + 1)
57
+ if child_html:
58
+ parts.append(child_html)
59
+
60
+ # Close shadow root
61
+ parts.append('</template>')
62
+
63
+ return ''.join(parts)
64
+
65
+ elif node.node_type == NodeType.ELEMENT_NODE:
66
+ parts = []
67
+ tag_name = node.tag_name.lower()
68
+
69
+ # Skip non-content elements
70
+ if tag_name in {'style', 'script', 'head', 'meta', 'link', 'title'}:
71
+ return ''
72
+
73
+ # Skip code tags with display:none - these often contain JSON state for SPAs
74
+ if tag_name == 'code' and node.attributes:
75
+ style = node.attributes.get('style', '')
76
+ # Check if element is hidden (display:none) - likely JSON data
77
+ if 'display:none' in style.replace(' ', '') or 'display: none' in style:
78
+ return ''
79
+ # Also check for bpr-guid IDs (LinkedIn's JSON data pattern)
80
+ element_id = node.attributes.get('id', '')
81
+ if 'bpr-guid' in element_id or 'data' in element_id or 'state' in element_id:
82
+ return ''
83
+
84
+ # Skip base64 inline images - these are usually placeholders or tracking pixels
85
+ if tag_name == 'img' and node.attributes:
86
+ src = node.attributes.get('src', '')
87
+ if src.startswith('data:image/'):
88
+ return ''
89
+
90
+ # Opening tag
91
+ parts.append(f'<{tag_name}')
92
+
93
+ # Add attributes
94
+ if node.attributes:
95
+ attrs = self._serialize_attributes(node.attributes)
96
+ if attrs:
97
+ parts.append(' ' + attrs)
98
+
99
+ # Handle void elements (self-closing)
100
+ void_elements = {
101
+ 'area',
102
+ 'base',
103
+ 'br',
104
+ 'col',
105
+ 'embed',
106
+ 'hr',
107
+ 'img',
108
+ 'input',
109
+ 'link',
110
+ 'meta',
111
+ 'param',
112
+ 'source',
113
+ 'track',
114
+ 'wbr',
115
+ }
116
+ if tag_name in void_elements:
117
+ parts.append(' />')
118
+ return ''.join(parts)
119
+
120
+ parts.append('>')
121
+
122
+ # Handle iframe content document
123
+ if tag_name in {'iframe', 'frame'} and node.content_document:
124
+ # Serialize iframe content
125
+ for child in node.content_document.children_nodes or []:
126
+ child_html = self.serialize(child, depth + 1)
127
+ if child_html:
128
+ parts.append(child_html)
129
+ else:
130
+ # Serialize shadow roots FIRST (for declarative shadow DOM)
131
+ if node.shadow_roots:
132
+ for shadow_root in node.shadow_roots:
133
+ child_html = self.serialize(shadow_root, depth + 1)
134
+ if child_html:
135
+ parts.append(child_html)
136
+
137
+ # Then serialize light DOM children (for slot projection)
138
+ for child in node.children:
139
+ child_html = self.serialize(child, depth + 1)
140
+ if child_html:
141
+ parts.append(child_html)
142
+
143
+ # Closing tag
144
+ parts.append(f'</{tag_name}>')
145
+
146
+ return ''.join(parts)
147
+
148
+ elif node.node_type == NodeType.TEXT_NODE:
149
+ # Return text content with basic HTML escaping
150
+ if node.node_value:
151
+ return self._escape_html(node.node_value)
152
+ return ''
153
+
154
+ elif node.node_type == NodeType.COMMENT_NODE:
155
+ # Skip comments to reduce noise
156
+ return ''
157
+
158
+ else:
159
+ # Unknown node type - skip
160
+ return ''
161
+
162
+ def _serialize_attributes(self, attributes: dict[str, str]) -> str:
163
+ """Serialize element attributes to HTML attribute string.
164
+
165
+ Args:
166
+ attributes: Dictionary of attribute names to values
167
+
168
+ Returns:
169
+ HTML attribute string (e.g., 'class="foo" id="bar"')
170
+ """
171
+ parts = []
172
+ for key, value in attributes.items():
173
+ # Skip href if not extracting links
174
+ if not self.extract_links and key == 'href':
175
+ continue
176
+
177
+ # Skip data-* attributes as they often contain JSON payloads
178
+ # These are used by modern SPAs (React, Vue, Angular) for state management
179
+ if key.startswith('data-'):
180
+ continue
181
+
182
+ # Handle boolean attributes
183
+ if value == '' or value is None:
184
+ parts.append(key)
185
+ else:
186
+ # Escape attribute value
187
+ escaped_value = self._escape_attribute(value)
188
+ parts.append(f'{key}="{escaped_value}"')
189
+
190
+ return ' '.join(parts)
191
+
192
+ def _escape_html(self, text: str) -> str:
193
+ """Escape HTML special characters in text content.
194
+
195
+ Args:
196
+ text: Raw text content
197
+
198
+ Returns:
199
+ HTML-escaped text
200
+ """
201
+ return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
202
+
203
+ def _escape_attribute(self, value: str) -> str:
204
+ """Escape HTML special characters in attribute values.
205
+
206
+ Args:
207
+ value: Raw attribute value
208
+
209
+ Returns:
210
+ HTML-escaped attribute value
211
+ """
212
+ return value.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#x27;')