如何在 Selenium WebDriver 中解决 ElementNotInteractableException?


如果元素在 DOM 中可用,但没有处于可以交互的状态,则会在 Selenium 中出现 ElementNotInteractableException。此异常的一些原因包括:

要与之交互的元素可能被另一个元素覆盖。元素的这种重叠可能是临时或永久的。要解决临时重叠,我们可以等待元素的预期条件。

我们可以等待覆盖元素的 elementToBeClickable 的预期条件不可见。或者,等待与我们想要交互的元素的 elementToBeClickable 的预期条件。

语法

WebDriverWait w= (new WebDriverWait(driver, 7));
w.until(ExpectedConditions
. elementToBeClickable (By.id("id of element")));
//alternate solution
w.until(ExpectedConditions
. invisibilityOfElementLocated(By.id("id of overlay element")));

要解决永久重叠,我们可以使用 JavaScript Executor 来执行单击操作。Selenium 使用 executeScript 方法来执行 JavaScript 命令。

语法

WebElement l = driver.findElement(By.id("id of element"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", l);

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
public class InteractableExceptionFix{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://login.yahoo.com/");
      //identify element
      WebElement l = driver.findElement(By.xpath("//input[@id='persistent']"));
      //JavascriptExecutor to click element
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("arguments[0].click();", l);
      boolean t = l.isSelected();
      if (t) {
         System.out.println("Checkbox is not checked");
      }else {
         System.out.println("Checkbox is checked");
      }
      driver.quit();
   }
}

输出

更新于:07-Apr-2021

3K+ 浏览量

开启你的 职业

通过完成课程获得认证

立即开始
广告
© . All rights reserved.