如何使用 Selenium 和 Action 类将鼠标悬停在父元素上,然后单击子元素 [英] How to mouse hover a parent element and subsequently click on child element using Selenium and Action class

查看:32
本文介绍了如何使用 Selenium 和 Action 类将鼠标悬停在父元素上,然后单击子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个测试,将鼠标悬停在下面有链接的元素上,然后单击子元素.我不断收到 NullPointerException.它以前工作过并再次停止工作.

I wrote a test to hover mouse on an Element which has a link underneath it and to click the subElement. I keep getting NullPointerException. It had work previously and stopped working again.

Actions mouseHover = new Actions(driver);
mouseHover.moveToElement(ParentElement);
mouseHover.moveToElement(subElement);
mouseHover.click(subElement);

推荐答案

根据您的代码尝试,您还没有为 Mouse Hover 调用 perform() 方法.您需要为元素引入 WebDriverWait 并且可以使用以下解决方案:

As per your code attempts you havn't invoked the perform() method for Mouse Hover. You need to induce WebDriverWait for the elements and can use the following solution:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
//other lines of code
Actions mouseHover = new Actions(driver);
mouseHover.moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOf(ParentElement)))).perform();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath(subElement))).click();

<小时>

更新

由于您仍然看到以下错误:


Update

As you are still seeing the error as:

 java.lang.NullPointerException at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:882) at org.openqa.selenium.interactions.Actions.<init>(Actions.java:68)

这意味着不能从这部分代码访问 WebDriver 实例,即 驱动程序.该问题可能与 drivernull 相关,因为您没有在 Test 类中扩展 Base 类.确保 驱动程序 可访问.

This implies that WebDriver instance i.e. the driver is not accessible from this part of the code. The issue may be related to driver being null as you did not extend the Base class in the Test class. Ensure that the driver is accessible.

这篇关于如何使用 Selenium 和 Action 类将鼠标悬停在父元素上,然后单击子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆