首页 > 解决方案 > 仅使用 Selenium 将鼠标悬停在元素上

问题描述

我试图简单地将鼠标悬停在使用 Selenium 代码的元素上。该元素出现在网页中并且是可点击的。

我不断收到此错误:

javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite. (Session info: chrome=80.0.3987.132) Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: 'TALANGEL-LP', ip: '172.17.17.148', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_152-release' Driver info: org.openqa.selenium.chrome.ChromeDriver

我的代码:

WebDriverWait wait = new WebDriverWait(browser,3);
elementToHoverOn = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("button[id='MyBtn']")));
new Actions(browser).moveToElement(elementToHoverOn).perform();

即使我尝试简单地使用 By.ID 查找元素,我也会得到相同的错误。我在其他线程上看到该元素必须是特定的,并且确实如此。

我在这里想念什么?

标签: javaselenium

解决方案


presenceOfElementLocated()不保证元素是可见的。相反,您需要诱导WebDriverWait并且visibilityOfElementLocated()您可以使用以下任一 Locator Strategies

  • cssSelector

    new Actions(browser).moveToElement(new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button#MyBtn")))).build().perform();
    
  • xpath

    new Actions(browser).moveToElement(new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[@id='MyBtn']")))).build().perform();
    

推荐阅读