WebAgents_ / tools /search_item_ctrl_f.py
Firoj112's picture
Upload 4 files
9cb4e3c verified
raw
history blame
1.26 kB
from typing import Any
from smolagents.tools import Tool
from selenium.webdriver.common.by import By
class SearchItemCtrlFTool(Tool):
name = "search_item_ctrl_f"
description = "Searches for text on the current page via Ctrl + F and jumps to the nth occurrence."
inputs = {
'text': {'type': 'str', 'description': 'The text to search for'},
'nth_result': {'type': 'int', 'description': 'Which occurrence to jump to (default: 1)'}
}
output_type = "str"
def forward(self, text: str, nth_result: int = 1, driver: Any = None) -> str:
if not driver:
raise ValueError("WebDriver instance is required.")
elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
if nth_result > len(elements):
raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
result = f"Found {len(elements)} matches for '{text}'."
elem = elements[nth_result - 1]
driver.execute_script("arguments[0].scrollIntoView(true);", elem)
result += f" Focused on element {nth_result} of {len(elements)}"
return result
def __init__(self, *args, **kwargs):
self.is_initialized = False