java - 如何使用 Java 在 Selenium WebDriver 中将鼠标移动到元素上来设置焦点?

标签 java selenium selenium-webdriver automated-tests focus

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

  1. 首先,进入StackOverflow主页。
  2. 然后,将鼠标移到用户按钮上,使其获得焦点。 (我们不必点击它,只需将鼠标悬停在它上面即可。)
  3. 现在,找到屏幕上的 Activity 元素(即 当前焦点),然后单击它。

我希望单击“用户”按钮,因为它当前处于焦点状态,但这种情况没有发生。相反,单击问题按钮。 这是我进行相同测试的代码。

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://stackoverflow.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 类没有聚焦该元素。这是一个问题,或者很多次我在 Firefox 浏览器中使用 Actions 类时遇到问题。

您仍然有一种替代方法来聚焦所需的元素,然后单击聚焦的元素,即 JavascriptExecutor

这是您的代码:

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

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

关于java - 如何使用 Java 在 Selenium WebDriver 中将鼠标移动到元素上来设置焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727083/

相关文章:

dd-MMM-yyyy 格式的 java.time.format.DateTimeParseException

java - 如何按日期对对象列表进行排序(java 集合,List<Object>)

java - 具有Java,IntelliJ和Gradle的Selenium-驱动程序可执行文件的路径必须由webdriver.gecko.driver系统属性设置

python - 如何使用 Python 访问我的 Firefox 配置文件中的页面

node.js - WebDriver 等待 n 秒

java - 是否可以将我自己的类(class)放入第 3 方包中?

java - 如何使用 firebase firestore android 中的数据列表

javascript - 使用 Selenium C# 将 Chrome 缩放设置为 100%

c# - 无法使用 C# 在 Selenium WebDriver 中使用现有的 Firefox 配置文件

python - 如何使 Selenium WebDriver 不等待整个页面加载