无法将鼠标悬停在xpath上

时间:2018-03-30 04:54:11

标签: java selenium selenium-webdriver webdriver mouseover

我正在使用以下代码将鼠标悬停在元素上

Webelement el=driver.findElement(By.xpath("/html/body/app-root/div/app-root/div/app-admin-app/app-header/div/div[3]/a"));
Actions act = new Actions(driver);
act.moveToElement(el).perform();

但它不起作用。

元素的HTML如下:

<a _ngcontent-c4="" class="ui label " style="width:100%">
  <img _ngcontent-c4="" 
       class="ui right spaced avatar image" 
       src="assets/images/avatar.png">admin </a>

2 个答案:

答案 0 :(得分:0)

根据 HTML ,该元素是 Angular 元素,因此您必须诱导 WebDriverWait ,然后鼠标悬停如下:

Actions act = new Actions(driver);
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='ui label']/img[@class='ui right spaced avatar image' and @src='assets/images/avatar.png']")));
act.moveToElement(elem).perform();

答案 1 :(得分:0)

尝试使用JavascriptExecutor类来执行相同的悬停功能:

导入JavascriptExecutor类:

import org.openqa.selenium.JavascriptExecutor;

并使用此方法代替Actions Class:

WebElement element= driver.findElement(By.xpath("//a/img[contains(@src,'assets/images/avatar.png')]"));

String mouseOver = "var evObj = document.createEvent('MouseEvents');" +
                    "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
                    "arguments[0].dispatchEvent(evObj);";

((JavascriptExecutor) driver).executeScript(mouseOver, element);

尝试一下,让我知道它是否适合你。