Firoj112 commited on
Commit
3064cc7
·
verified ·
1 Parent(s): e9ed5be

Create interact_element.py

Browse files
Files changed (1) hide show
  1. tools/interact_element.py +66 -0
tools/interact_element.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents.tools import Tool
2
+ from helium import write, press, click, Text, Link, S
3
+ from selenium.webdriver.common.keys import Keys
4
+
5
+ def interact_element(driver, selector=None, text=None, action="click", input_text=None, key=None):
6
+ """
7
+ Interact with a web element (click, fill text, press keys).
8
+
9
+ Args:
10
+ driver: Selenium WebDriver instance
11
+ selector (str): CSS selector to target the element (optional)
12
+ text (str): Text to locate the element (optional, for Helium)
13
+ action (str): Action to perform ('click', 'fill', 'press') (default: 'click')
14
+ input_text (str): Text to input if action='fill' (optional)
15
+ key (str): Key to press if action='press' (e.g., 'ENTER') (optional)
16
+
17
+ Returns:
18
+ str: Result of the interaction
19
+ """
20
+ try:
21
+ if selector:
22
+ element = driver.find_element(By.CSS_SELECTOR, selector)
23
+ elif text:
24
+ if action == "click" and Link(text).exists():
25
+ element = Link(text).web_element
26
+ else:
27
+ element = Text(text).web_element
28
+ else:
29
+ return "Must provide selector or text"
30
+
31
+ if action == "click":
32
+ click(element)
33
+ return f"Clicked element with {selector or text}"
34
+ elif action == "fill":
35
+ if not input_text:
36
+ return "input_text required for fill action"
37
+ write(input_text, into=element)
38
+ return f"Filled {input_text} into element with {selector or text}"
39
+ elif action == "press":
40
+ if not key:
41
+ return "key required for press action"
42
+ key_map = {"ENTER": Keys.ENTER, "TAB": Keys.TAB, "RETURN": Keys.RETURN}
43
+ if key.upper() in key_map:
44
+ element.send_keys(key_map[key.upper()])
45
+ else:
46
+ press(key)
47
+ return f"Pressed {key} on element with {selector or text}"
48
+ else:
49
+ return f"Unknown action: {action}"
50
+ except Exception as e:
51
+ return f"Failed to interact with element {selector or text}: {str(e)}"
52
+
53
+ # Register the tool
54
+ tool = Tool(
55
+ name="interact_element",
56
+ description="Interacts with a web element (click, fill text, press keys).",
57
+ inputs={
58
+ "selector": {"type": "str", "default": null, "description": "CSS selector to target element"},
59
+ "text": {"type": "str", "default": null, "description": "Text to locate element"},
60
+ "action": {"type": "str", "default": "click", "description": "Action: 'click', 'fill', or 'press'"},
61
+ "input_text": {"type": "str", "default": null, "description": "Text to input for fill action"},
62
+ "key": {"type": "str", "default": null, "description": "Key to press (e.g., 'ENTER')"}
63
+ },
64
+ output_type="str",
65
+ function=interact_element
66
+ )