How to mouse hover a parent element and subsequently click on child element using Selenium and Action class

早过忘川 提交于 2020-01-30 05:17:52

问题


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);

回答1:


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)

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.

Related Discussions:

  • What is this Error: at com.google.common.base.Preconditions.checkNotNull
  • Why does the NullPointerException occur on the Selenium driver?



回答2:


It may be trying to click the element before it appears. Try to use a web driver wait before you move to the subelement. ( Since it worked previously I guess this should be the issue )

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.LOCATOR("subelement")));

It'll look like,

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

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.LOCATOR("subelement")));

mouseHover.moveToElement(subElement);
mouseHover.click(subElement);

Cheerz



来源:https://stackoverflow.com/questions/52384816/how-to-mouse-hover-a-parent-element-and-subsequently-click-on-child-element-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!