如何使用 Java 在 Selenium WebDriver 中实现鼠标悬停功能?

seleniumautomation testingtesting tools

鼠标悬停在某个元素上会触发该元素的事件。例如,当我们将鼠标悬停在网页的菜单上时,子菜单就会出现。因此,当鼠标悬停在某个元素上时,就会触发该事件。

从上图可以看出,当鼠标悬停在Packages菜单上时,文本颜色会发生变化,同时工具提示也会显示。Selenium 的 Actions 类包含多个用于鼠标光标移动的 API。

使用 moveToElement() 方法可以实现鼠标移动。我们需要导入 `org.openqa.selenium.interactions.Actions` 类。除了 `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://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // 识别元素
      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();
   }
}

输出


相关文章