如何使用 Java 在 Selenium WebDriver 中将鼠标移到元素上?

How to set focus on element on moving the mouse over it in Selenium WebDriver using Java?

我是 Selenium WebDriver 的初学者,我在 Whosebug 主页上使用这个测试。这些将是我的测试步骤:

  1. 首先,转到 Whosebug 的主页。
  2. 然后,将鼠标移到 Users 按钮上,使其成为焦点。 (我们不必点击它,只需将鼠标悬停在它上面即可。)
  3. 现在,找到屏幕上的活动元素(即 当前聚焦)然后点击它。

我希望用户按钮被点击,因为它当前处于焦点状态,但没有发生。而是单击 Questions 按钮。 这是我的相同测试代码。

package insertCartridge;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Practice {
   public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    System.setProperty("webdriver.gecko.driver", "D:\SELENIUM\geckodriver-v0.18.0-win64\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
    String baseUrl = "https://whosebug.com/";
    driver.get(baseUrl);
    driver.manage().window().setSize(new Dimension(1920, 1080));
    WebElement Users = driver.findElement(By.xpath("/html/body/header/div/div[1]/nav/ol/li[5]"));
    Thread.sleep(3000);
    Actions builder = new Actions(driver);
    builder.moveToElement(Users).perform();
    Thread.sleep(3000);
    driver.switchTo().activeElement().click();
 }
}

我不明白为什么我没有得到预期的输出。请帮忙

我不知道为什么 Actions class 没有聚焦元素。这是一个问题或其他问题,因为我在 Firefox 浏览器中使用 Actions class 时遇到了很多问题。

还有一种方法可以将焦点放在所需元素上,然后单击焦点元素,即 JavascriptExecutor

这是您的代码:

JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('nav-users').focus();");

System.out.println(driver.switchTo().activeElement().getTagName());       
driver.switchTo().activeElement().click();