如何在使用 Java 的 Selenium WebDriver 中執行滑鼠懸停功能?
對元素執行滑鼠懸停操作以觸發該元素上的事件。如果我們懸停在網頁的選單上,則會出現子選單。因此,當懸停在元素上時會觸發此事件。
從上圖可以明顯看出,在懸停在套餐 選單上時,文字顏色會隨著工具提示顯示而改變。Selenium 有一個 Actions 類,其中包含用於滑鼠游標移動的多個 API。
moveToElement() 方法用於執行滑鼠移動。我們必須匯入 org.openqa.selenium.interactions.Actions 以獲取 Action 類。除了 moveToElement() 之外,我們還必須使用 perform() 方法來進行滑鼠移動。
示例
程式碼實現。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.interactions.Actions; public class MouseHover{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://tutorialspoint.tw/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.xpath("//span[text()='Jobs']")); // Actions class with moveToElement() Actions a = new Actions(driver); a.moveToElement(l).perform(); System.out.println("Tooltip: "+ l.getText()); driver.quit(); } }
輸出
廣告