-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathbrowser_tool.py
More file actions
1813 lines (1534 loc) 路 77.2 KB
/
Copy pathbrowser_tool.py
File metadata and controls
1813 lines (1534 loc) 路 77.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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.common.exceptions import TimeoutException, StaleElementReferenceException
from typing import Dict, Any, List, Optional, Tuple, Union
from pydantic import Field
from .tool import Tool,Toolkit
from ..core.module import BaseModule
from evoagentx.core.logging import logger
import html2text
import time
# Define selector map as a constant to avoid repetition
SELECTOR_MAP = {
"css": By.CSS_SELECTOR,
"xpath": By.XPATH,
"id": By.ID,
"class": By.CLASS_NAME,
"name": By.NAME,
"tag": By.TAG_NAME,
}
class BrowserBase(BaseModule):
"""
A tool for interacting with web browsers using Selenium.
Allows agents to navigate to URLs, interact with elements, extract information,
and more from web pages.
Key Features:
- Auto-initialization: Browser is automatically initialized when any method is first called
- Auto-cleanup: Browser is automatically closed when the instance is destroyed
- No manual initialization or cleanup required
"""
timeout: int = Field(default=10, description="Default timeout in seconds for browser operations")
browser_type: str = Field(default="chrome", description="Type of browser to use ('chrome', 'firefox', 'safari', 'edge')")
headless: bool = Field(default=False, description="Whether to run the browser in headless mode")
user_data_dir: Optional[str] = Field(default=None, description="User data directory for persistent browser sessions")
def __init__(
self,
name: str = "Browser Tool",
browser_type: str = "chrome",
headless: bool = False,
timeout: int = 10,
**kwargs
):
"""
Initialize the browser tool with Selenium WebDriver.
Args:
name (str): Name of the tool
browser_type (str): Type of browser to use ('chrome', 'firefox', 'safari', 'edge')
headless (bool): Whether to run the browser in headless mode
timeout (int): Default timeout in seconds for browser operations
**kwargs: Additional keyword arguments for parent class initialization
"""
# Pass to parent class initialization
super().__init__(name=name, timeout=timeout, browser_type=browser_type, headless=headless, **kwargs)
self.driver = None
# Storage for element references from snapshots
self.element_references = {}
# Helper methods to reduce duplication
def _check_driver_initialized(self) -> Union[None, Dict[str, Any]]:
"""
Check if the browser driver is initialized. If not, initialize it automatically.
Returns:
Union[None, Dict[str, Any]]: None if driver is initialized, error response if initialization fails
"""
if not self.driver:
# Automatically initialize the browser
init_result = self.initialize_browser()
if init_result["status"] == "error":
return init_result
return None
def _get_selector_by_type(self, selector_type: str) -> Union[str, Dict[str, Any]]:
"""
Get the Selenium By selector for the given selector type.
Args:
selector_type (str): Type of selector ('css', 'xpath', 'id', 'class', 'name', 'tag')
Returns:
Union[str, Dict[str, Any]]: The By selector or error response
"""
by_type = SELECTOR_MAP.get(selector_type.lower())
if not by_type:
return {"status": "error", "message": f"Invalid selector type: {selector_type}"}
return by_type
def _wait_for_page_load(self, timeout: Optional[int] = None) -> bool:
"""
Wait for the page to load completely.
Args:
timeout (int, optional): Custom timeout for this operation
Returns:
bool: True if page loaded, False if timed out
"""
timeout = timeout or self.timeout
try:
WebDriverWait(self.driver, timeout).until(
lambda driver: driver.execute_script("return document.readyState") == "complete"
)
return True
except TimeoutException:
return False
def _parse_element_reference(self, ref: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:
"""
Parse an element reference into selector type and selector.
Args:
ref (str): Element reference ID from the page snapshot
Returns:
Tuple[Optional[str], Optional[str], Optional[str]]:
(selector_type, selector, error_message) - error_message is None if successful
"""
if not self.element_references:
return None, None, "No page snapshot available. Use browser_snapshot or navigate_to_url first."
stored_ref = self.element_references.get(ref)
if not stored_ref:
return None, None, f"Element reference '{ref}' not found. Use browser_snapshot or navigate_to_url first."
# Parse the stored reference to get selector and type
if ":" in stored_ref:
ref_parts = stored_ref.split(":", 1)
if len(ref_parts) != 2:
return None, None, f"Invalid stored reference format: {stored_ref}"
selector_type, selector = ref_parts
return selector_type, selector, None
return None, None, f"Invalid stored reference format: {stored_ref}"
def _find_element_with_wait(self, by_type: str, selector: str,
timeout: Optional[int] = None,
wait_condition=EC.presence_of_element_located) -> Tuple[Optional[Any], Optional[str]]:
"""
Find an element on the page with wait condition.
Args:
by_type (str): Selenium By selector type
selector (str): The selector string
timeout (int, optional): Custom timeout for this operation
wait_condition: The EC condition to wait for
Returns:
Tuple[Optional[Any], Optional[str]]: (element, error_message) - error_message is None if successful
"""
timeout = timeout or self.timeout
try:
element = WebDriverWait(self.driver, timeout).until(
wait_condition((by_type, selector))
)
return element, None
except TimeoutException:
return None, f"Element not found or condition not met with selector: {selector}"
except Exception as e:
logger.error(f"Error finding element {selector}: {str(e)}")
return None, str(e)
def _handle_function_params(self, function_params: Optional[list],
function_name: str,
param_mapping: Dict[str, str]) -> Dict[str, Any]:
"""
Extract parameters from nested function_params format.
Args:
function_params (list, optional): Nested function parameters
function_name (str): The function name to look for
param_mapping (Dict[str, str]): Mapping of parameter names
Returns:
Dict[str, Any]: Extracted parameters
"""
result = {}
if not function_params:
return result
for param in function_params:
fn_name = param.get("function_name", "")
if fn_name == function_name or fn_name in param_mapping.get("alt_names", []):
args = param.get("function_args", {})
for param_name, result_name in param_mapping.items():
if param_name == "alt_names":
continue
if param_name in args:
result[result_name] = args[param_name]
break
return result
# Original methods with improved implementation using the helper methods
def initialize_browser(self, function_params: list = None) -> Dict[str, Any]:
"""
Start or restart a browser session. This method is called automatically when needed.
Note: This method is now called automatically by other browser methods when the browser
is not initialized. Manual initialization is no longer required.
This function supports multiple parameter styles:
1. Standard style: no parameters
2. Nested function_params style:
function_params=[{"function_name": "initialize_browser", "function_args": {}}]
Args:
function_params (list, optional): Nested function parameters
Returns:
Dict[str, Any]: Status information about the browser initialization
"""
try:
if self.driver:
# Close any existing session
try:
self.driver.quit()
except Exception as e:
logger.warning(f"Error closing existing browser session: {str(e)}")
options = None
if self.browser_type == "chrome":
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
options = Options()
if self.headless:
options.add_argument("--headless")
# Add GPU-related stability options
options.add_argument("--disable-gpu")
options.add_argument("--disable-gpu-sandbox")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# Add user data directory for persistent sessions
if self.user_data_dir:
options.add_argument(f"--user-data-dir={self.user_data_dir}")
logger.info(f"Using user data directory: {self.user_data_dir}")
# Create service with Chrome executable path
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=options)
elif self.browser_type == "firefox":
from selenium.webdriver.firefox.options import Options
options = Options()
if self.headless:
options.add_argument("--headless")
self.driver = webdriver.Firefox(options=options)
elif self.browser_type == "safari":
self.driver = webdriver.Safari()
elif self.browser_type == "edge":
from selenium.webdriver.edge.options import Options
options = Options()
if self.headless:
options.add_argument("--headless")
# Add GPU-related stability options
options.add_argument("--disable-gpu")
options.add_argument("--disable-gpu-sandbox")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# Add user data directory for persistent sessions
if self.user_data_dir:
options.add_argument(f"--user-data-dir={self.user_data_dir}")
logger.info(f"Using user data directory: {self.user_data_dir}")
self.driver = webdriver.Edge(options=options)
else:
return {"status": "error", "message": f"Unsupported browser type: {self.browser_type}"}
self.driver.set_page_load_timeout(self.timeout)
return {"status": "success", "message": f"Browser {self.browser_type} initialized successfully"}
except Exception as e:
logger.error(f"Error initializing browser: {str(e)}")
return {"status": "error", "message": str(e)}
def navigate_to_url(self, url: str = None, timeout: int = None,
function_params: list = None) -> Dict[str, Any]:
"""
Navigate to a URL and capture a snapshot of the page. This provides element references used for interaction.
This function supports multiple parameter styles:
1. Standard style: url parameter
2. Nested function_params style:
function_params=[{"function_name": "navigate_to_url", "function_args": {"url": "..."}}]
Args:
url (str, optional): The complete URL (with https://) to navigate to
timeout (int, optional): Custom timeout in seconds (default: 10)
function_params (list, optional): Nested function parameters
Returns:
Dict[str, Any]: Information about the navigation result and page snapshot
"""
# Check if browser is initialized (will auto-initialize if needed)
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
# Handle nested function_params format
if function_params and not url:
params = self._handle_function_params(
function_params,
"navigate_to_url",
{"url": "url", "timeout": "timeout", "alt_names": ["browser_navigate"]}
)
url = params.get("url")
timeout = params.get("timeout", timeout)
if not url:
return {"status": "error", "message": "URL parameter is required"}
timeout = timeout or self.timeout
try:
self.driver.get(url)
# Wait for page to load
page_loaded = self._wait_for_page_load(timeout)
if not page_loaded:
logger.warning(f"Page load timeout for URL: {url}, but continuing with snapshot")
# Automatically take a snapshot of the page
snapshot_result = self.browser_snapshot()
if snapshot_result["status"] == "success":
return {
"status": "success",
"url": url,
"title": self.driver.title,
"current_url": self.driver.current_url,
"snapshot": {
"interactive_elements": snapshot_result.get("interactive_elements", [])
}
}
else:
# Return navigation success but note snapshot failure
return {
"status": "partial_success",
"url": url,
"title": self.driver.title,
"current_url": self.driver.current_url,
"snapshot_error": snapshot_result.get("message", "Unknown error capturing snapshot")
}
except TimeoutException:
return {"status": "timeout", "message": f"Timed out loading URL: {url}"}
except Exception as e:
logger.error(f"Error navigating to URL {url}: {str(e)}")
return {"status": "error", "message": str(e)}
def find_element(self, selector: str, selector_type: str = "css", timeout: int = None) -> Dict[str, Any]:
"""
Find an element on the current page and return information about it.
Args:
selector (str): The selector to find the element
selector_type (str): Type of selector ('css', 'xpath', 'id', 'class', 'name', 'tag')
timeout (int, optional): Custom timeout for this operation
Returns:
Dict[str, Any]: Information about the found element
"""
# Check if browser is initialized
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
timeout = timeout or self.timeout
# Get the selector type
by_type = self._get_selector_by_type(selector_type)
if isinstance(by_type, dict): # Error response
return by_type
try:
# Find the element
element, error = self._find_element_with_wait(
by_type, selector, timeout, EC.presence_of_element_located
)
if error:
return {"status": "not_found", "message": f"Element not found with {selector_type}: {selector}"}
# Extract element properties
element_properties = self._extract_element_properties(element, selector)
return {
"status": "success",
"element": element_properties
}
except Exception as e:
logger.error(f"Error finding element {selector}: {str(e)}")
return {"status": "error", "message": str(e)}
def _extract_element_properties(self, element, selector: str) -> Dict[str, Any]:
"""
Extract common properties from a WebElement.
Args:
element: The Selenium WebElement
selector (str): The selector used to find the element (for error messages)
Returns:
Dict[str, Any]: Element properties
"""
element_properties = {
"text": element.text,
"tag_name": element.tag_name,
"is_displayed": element.is_displayed(),
"is_enabled": element.is_enabled(),
}
# Get attributes safely
for attr in ["href", "id", "class"]:
try:
value = element.get_attribute(attr)
if value:
element_properties[attr] = value
except StaleElementReferenceException:
logger.warning(f"Element became stale when trying to get {attr} attribute for {selector}")
except Exception as e:
logger.warning(f"Could not get {attr} attribute for {selector}: {str(e)}")
return element_properties
def find_multiple_elements(self, selector: str, selector_type: str = "css", timeout: int = None) -> Dict[str, Any]:
"""
Find multiple elements on the current page and return information about them.
Args:
selector (str): The selector to find the elements
selector_type (str): Type of selector ('css', 'xpath', 'id', 'class', 'name', 'tag')
timeout (int, optional): Custom timeout for this operation
Returns:
Dict[str, Any]: Information about the found elements
"""
# Check if browser is initialized
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
timeout = timeout or self.timeout
# Get the selector type
by_type = self._get_selector_by_type(selector_type)
if isinstance(by_type, dict): # Error response
return by_type
try:
# First check if at least one element exists
element, error = self._find_element_with_wait(
by_type, selector, timeout, EC.presence_of_element_located
)
if error:
return {"status": "not_found", "message": f"No elements found with {selector_type}: {selector}"}
# Then get all matching elements
elements = self.driver.find_elements(by_type, selector)
# Extract element properties
elements_properties = []
for idx, element in enumerate(elements):
try:
element_properties = self._extract_element_properties(element, f"{selector}[{idx}]")
element_properties["index"] = idx
elements_properties.append(element_properties)
except StaleElementReferenceException:
logger.warning(f"Element {idx} became stale while extracting properties")
except Exception as e:
logger.warning(f"Error extracting properties for element {idx}: {str(e)}")
return {
"status": "success",
"count": len(elements_properties),
"elements": elements_properties
}
except Exception as e:
logger.error(f"Error finding elements {selector}: {str(e)}")
return {"status": "error", "message": str(e)}
def click_element(self, selector: str, selector_type: str = "css", timeout: int = None) -> Dict[str, Any]:
"""
Click on an element on the current page.
Args:
selector (str): The selector to find the element
selector_type (str): Type of selector ('css', 'xpath', 'id', 'class', 'name', 'tag')
timeout (int, optional): Custom timeout for this operation
Returns:
Dict[str, Any]: Result of the click operation
"""
# Check if browser is initialized
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
timeout = timeout or self.timeout
# Get the selector type
by_type = self._get_selector_by_type(selector_type)
if isinstance(by_type, dict): # Error response
return by_type
try:
# Find and click the element
element, error = self._find_element_with_wait(
by_type, selector, timeout, EC.element_to_be_clickable
)
if error:
return {"status": "not_found", "message": f"Element not clickable with {selector_type}: {selector}"}
element.click()
# Wait for page to load after click
page_loaded = self._wait_for_page_load(timeout)
if not page_loaded:
return {
"status": "partial_success",
"message": "Element clicked, but page load timed out",
"selector": selector,
"current_url": self.driver.current_url
}
return {
"status": "success",
"message": f"Clicked element with {selector_type}: {selector}",
"current_url": self.driver.current_url,
"title": self.driver.title
}
except Exception as e:
logger.error(f"Error clicking element {selector}: {str(e)}")
return {"status": "error", "message": str(e)}
def input_text(self, element: str = None, ref: str = None, text: str = None,
submit: bool = False, slowly: bool = True,
function_params: list = None) -> Dict[str, Any]:
"""
Type text into a form field, search box, or other input element using a reference ID from a snapshot.
This function only works with element references from a snapshot. Use browser_snapshot
or navigate_to_url first to capture the page elements.
This function supports multiple parameter styles:
1. Standard style: element (description), ref (element ID), text
2. Nested function_params style:
function_params=[{"function_name": "browser_type", "function_args": {...}}]
Args:
element (str, optional): Human-readable description of the element (e.g., 'Search field', 'Username input')
ref (str, optional): Element ID from the page snapshot (e.g., 'e0', 'e1', 'e2') - NOT a CSS selector
text (str, optional): Text to input into the element
submit (bool): Press Enter after typing to submit forms (default: false)
slowly (bool): Type one character at a time to trigger JS events (default: true)
function_params (list, optional): Nested function parameters
Returns:
Dict[str, Any]: Result of the text input operation
"""
# Check if browser is initialized
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
# Handle nested function_params format
if function_params:
params = self._handle_function_params(
function_params,
"input_text",
{"element": "element", "ref": "ref", "text": "text",
"submit": "submit", "slowly": "slowly", "alt_names": ["browser_type"]}
)
element = params.get("element", element)
ref = params.get("ref", ref)
text = params.get("text", text)
if "submit" in params:
submit = params["submit"]
if "slowly" in params:
slowly = params["slowly"]
if not ref or not text:
return {"status": "error", "message": "Both ref and text parameters are required"}
# Parse the reference
selector_type, selector, error = self._parse_element_reference(ref)
if error:
return {"status": "error", "message": error}
# Use a human-readable description or the ref ID if not provided
element_desc = element or ref
# Get the selector type
by_type = self._get_selector_by_type(selector_type)
if isinstance(by_type, dict): # Error response
return by_type
try:
# Find the element
web_element, error = self._find_element_with_wait(
by_type, selector, self.timeout, EC.element_to_be_clickable
)
if error:
return {"status": "not_found", "message": f"Element not found: {element_desc}"}
# Clear existing content
web_element.clear()
# Type text
if slowly:
# Type character by character
for char in text:
web_element.send_keys(char)
# Small delay between keypresses
time.sleep(0.05)
else:
# Type all at once
web_element.send_keys(text)
# Submit if requested
if submit:
from selenium.webdriver.common.keys import Keys
web_element.send_keys(Keys.ENTER)
# Wait for page to load after submission
page_loaded = self._wait_for_page_load(self.timeout)
if not page_loaded:
# Take a new snapshot after submitting
self.browser_snapshot()
return {
"status": "partial_success",
"message": "Text entered and submitted, but page load timed out",
"element": element_desc,
"text": text
}
# Take a new snapshot after submitting
snapshot_result = self.browser_snapshot()
if snapshot_result["status"] != "success":
logger.warning(f"Failed to capture snapshot after form submission: {snapshot_result.get('message')}")
return {
"status": "success",
"message": f"Successfully input text into {element_desc}" +
(" and submitted" if submit else ""),
"element": element_desc,
"text": text
}
except TimeoutException:
return {"status": "not_found", "message": f"Element not found: {element_desc}"}
except Exception as e:
logger.error(f"Error inputting text to element {element_desc}: {str(e)}")
return {"status": "error", "message": str(e)}
def get_page_content(self) -> Dict[str, Any]:
"""
Get the current page title, URL and body content.
Returns:
Dict[str, Any]: Information about the current page
"""
# Check if browser is initialized (will auto-initialize if needed)
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
try:
# Get title and URL
title = self.driver.title
current_url = self.driver.current_url
# Extract only the body content using JavaScript
body_content = self.driver.execute_script("""
var body = document.body;
return body ? body.outerHTML : "";
""")
# Get a summary of key elements for easier navigation
element_summary = self.driver.execute_script("""
// Get common interactive elements
var summary = {
links: [],
buttons: [],
inputs: [],
forms: []
};
// Get links
var links = document.querySelectorAll('a');
for (var i = 0; i < Math.min(links.length, 20); i++) {
var link = links[i];
summary.links.push({
text: link.textContent.trim().substring(0, 50),
href: link.getAttribute('href'),
id: link.id,
class: link.className
});
}
// Get buttons
var buttons = document.querySelectorAll('button, input[type="button"], input[type="submit"]');
for (var i = 0; i < Math.min(buttons.length, 20); i++) {
var button = buttons[i];
summary.buttons.push({
text: button.textContent ? button.textContent.trim().substring(0, 50) : button.value,
id: button.id,
class: button.className,
type: button.type
});
}
// Get inputs
var inputs = document.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select');
for (var i = 0; i < Math.min(inputs.length, 20); i++) {
var input = inputs[i];
summary.inputs.push({
type: input.type,
name: input.name,
id: input.id,
placeholder: input.placeholder
});
}
// Get forms
var forms = document.querySelectorAll('form');
for (var i = 0; i < Math.min(forms.length, 10); i++) {
var form = forms[i];
summary.forms.push({
id: form.id,
action: form.action,
method: form.method
});
}
return summary;
""")
return {
"status": "success",
"title": title,
"url": current_url,
"body_content": body_content,
"element_summary": element_summary
}
except Exception as e:
logger.error(f"Error getting page content: {str(e)}")
return {"status": "error", "message": str(e)}
def switch_to_frame(self, frame_reference: str, reference_type: str = "index") -> Dict[str, Any]:
"""
Switch to a frame on the page.
Args:
frame_reference (str): Reference to the frame (index, name, or ID)
reference_type (str): Type of reference ('index', 'name', 'id', 'element')
Returns:
Dict[str, Any]: Result of the frame switch operation
"""
# Check if browser is initialized (will auto-initialize if needed)
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
try:
if reference_type == "index":
try:
index = int(frame_reference)
self.driver.switch_to.frame(index)
except ValueError:
return {"status": "error", "message": f"Invalid frame index: {frame_reference}"}
elif reference_type == "name" or reference_type == "id":
self.driver.switch_to.frame(frame_reference)
elif reference_type == "element":
# First find the element
selector_parts = frame_reference.split(":", 1)
if len(selector_parts) != 2:
return {"status": "error", "message": "Element reference must be in format 'selector_type:selector'"}
selector_type, selector = selector_parts
element_result = self.find_element(selector, selector_type)
if element_result["status"] != "success":
return {"status": "error", "message": f"Could not find frame element: {element_result['message']}"}
# Get the actual WebElement (not just the properties)
selector_map = {
"css": By.CSS_SELECTOR,
"xpath": By.XPATH,
"id": By.ID,
"class": By.CLASS_NAME,
"name": By.NAME,
"tag": By.TAG_NAME,
}
by_type = selector_map.get(selector_type.lower())
element = self.driver.find_element(by_type, selector)
self.driver.switch_to.frame(element)
else:
return {"status": "error", "message": f"Invalid reference type: {reference_type}"}
return {
"status": "success",
"message": f"Switched to frame using {reference_type}: {frame_reference}"
}
except Exception as e:
logger.error(f"Error switching to frame {frame_reference}: {str(e)}")
return {"status": "error", "message": str(e)}
def switch_to_window(self, window_reference: str, reference_type: str = "index") -> Dict[str, Any]:
"""
Switch to a window or tab.
Args:
window_reference (str): Reference to the window (index, handle, or title)
reference_type (str): Type of reference ('index', 'handle', 'title')
Returns:
Dict[str, Any]: Result of the window switch operation
"""
# Check if browser is initialized (will auto-initialize if needed)
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
try:
window_handles = self.driver.window_handles
if not window_handles:
return {"status": "error", "message": "No window handles available"}
if reference_type == "index":
try:
index = int(window_reference)
if index < 0 or index >= len(window_handles):
return {"status": "error", "message": f"Window index out of range: {index}"}
self.driver.switch_to.window(window_handles[index])
except ValueError:
return {"status": "error", "message": f"Invalid window index: {window_reference}"}
elif reference_type == "handle":
if window_reference not in window_handles:
return {"status": "error", "message": f"Window handle not found: {window_reference}"}
self.driver.switch_to.window(window_reference)
elif reference_type == "title":
current_handle = self.driver.current_window_handle
window_found = False
for handle in window_handles:
try:
self.driver.switch_to.window(handle)
if self.driver.title == window_reference:
window_found = True
break
except Exception:
pass
if not window_found:
# Switch back to the original window
self.driver.switch_to.window(current_handle)
return {"status": "error", "message": f"No window with title '{window_reference}' found"}
else:
return {"status": "error", "message": f"Invalid reference type: {reference_type}"}
return {
"status": "success",
"message": f"Switched to window using {reference_type}: {window_reference}",
"title": self.driver.title,
"url": self.driver.current_url
}
except Exception as e:
logger.error(f"Error switching to window {window_reference}: {str(e)}")
return {"status": "error", "message": str(e)}
def select_dropdown_option(self, select_selector: str,
option_value: str,
select_by: str = "value",
selector_type: str = "css") -> Dict[str, Any]:
"""
Select an option from a dropdown
select_by can be 'value', 'text', or 'index'
Args:
select_selector (str): The selector to find the dropdown element
option_value (str): The value to select (depends on select_by)
select_by (str): Method to select by ('value', 'text', 'index')
selector_type (str): Type of selector for the dropdown
Returns:
Dict[str, Any]: Result of the selection operation
"""
# Check if browser is initialized
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
try:
from selenium.webdriver.support.ui import Select
# Get the selector type
by_type = self._get_selector_by_type(selector_type)
if isinstance(by_type, dict): # Error response
return by_type
# Find the dropdown element
element, error = self._find_element_with_wait(
by_type, select_selector, self.timeout, EC.presence_of_element_located
)
if error:
return {"status": "not_found", "message": f"Dropdown element not found with {selector_type}: {select_selector}"}
# Create select object
select = Select(element)
# Select based on method
if select_by.lower() == "value":
select.select_by_value(option_value)
elif select_by.lower() == "text":
select.select_by_visible_text(option_value)
elif select_by.lower() == "index":
try:
select.select_by_index(int(option_value))
except ValueError:
return {"status": "error", "message": f"Invalid index value: {option_value}. Must be an integer."}
else:
return {"status": "error", "message": f"Invalid select_by option: {select_by}"}
return {"status": "success", "message": f"Selected option with {select_by}: {option_value}"}
except Exception as e:
logger.error(f"Error selecting dropdown option: {str(e)}")
return {"status": "error", "message": str(e)}
def close_browser(self) -> Dict[str, Any]:
"""
Close the browser and end the session. Call this when you're done to free resources.
Returns:
Dict[str, Any]: Status of the browser closure
"""
if not self.driver:
return {"status": "success", "message": "Browser already closed"}
try:
self.driver.quit()
self.driver = None
return {"status": "success", "message": "Browser closed successfully"}
except Exception as e:
logger.error(f"Error closing browser: {str(e)}")
return {"status": "error", "message": str(e)}
def browser_click(self, element: str = None, ref: str = None,
function_params: list = None) -> Dict[str, Any]:
"""
Click on a button, link, or other clickable element using a reference ID from a snapshot.
This function only works with element references from a snapshot. You MUST call browser_snapshot
or navigate_to_url first to capture the page elements.
Common usage pattern:
1. First get a snapshot: browser_snapshot() or navigate_to_url()
2. Find the element reference (e.g. 'e0', 'e1') from the snapshot's interactive_elements
3. Use that reference to click: browser_click(element='Login button', ref='e0')
This function supports multiple parameter styles:
1. Standard style: element (description), ref (element ID)
2. Nested function_params style:
function_params=[{"function_name": "browser_click", "function_args": {...}}]
Args:
element (str, optional): Human-readable description of what you're clicking (e.g., 'Login button', 'Next page link')
ref (str, optional): Element ID from the page snapshot (e.g., 'e0', 'e1', 'e2') - NOT a CSS selector
function_params (list, optional): Nested function parameters
Returns:
Dict[str, Any]: Result of the click operation with detailed feedback
"""
# Check if browser is initialized
driver_check = self._check_driver_initialized()
if driver_check:
return driver_check
# Handle nested function_params format
if function_params and not ref:
params = self._handle_function_params(
function_params,
"browser_click",
{"element": "element", "ref": "ref"}
)
element = params.get("element", element)
ref = params.get("ref", ref)