如何在使用 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.com/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();
   }
}

输出

更新于: 2020-08-28

757 次浏览

开启你的 职业

完成课程即可获得认证

立即开始
广告
© . All rights reserved.