繁体   English   中英

如何鼠标悬停父元素,然后使用Selenium和Action类单击子元素

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

我写了一个测试,将鼠标悬停在一个Element上,该元素下面有一个链接并单击subElement。 我一直得到NullPointerException。 它之前有工作,并再次停止工作。

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

它可能试图在元素出现之前单击它。 在移动到子元素之前尝试使用Web驱动程序等待。 (因为它之前有用,我猜这应该是问题)

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

它看起来像,

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

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

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

更新

因为您仍然看到错误:

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

这意味着WebDriver实例即驱动程序无法从代码的这一部分访问。 该问题可能与驱动程序null有关,因为您没有在Test类中扩展Base类。 确保可以访问驱动程序

相关讨论:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM