Selenium 中有哪些重要的异常?


Selenium 中各种重要的异常列举如下:

  • TimeoutException − 如果操作在特定时间内未完成,则抛出此异常。如果页面元素即使在等待后也没有加载。

driver.manage().timeouts().implicitlyWait(15,TimeUnit.SECONDS) ;
driver.get(“https://tutorialspoint.com/index.htm” );

在上面的程序中,添加了 15 秒的隐式等待。如果页面https://tutorialspoint.com/index.htm在 15 秒内未加载,则会抛出 TimeoutException。

  • NoSuchElementException − 如果页面上不存在具有特定属性的 Web 元素,则会发生此异常。此异常类是 NotFoundException 的子类,如果驱动程序未能成功定位元素,则会抛出此异常。

driver.findElement(By.name("tutorial-test")).click();
//Exception Handling:
try {
   driver.findElement(By.name("tutorial-test")).click();
} catch (NoSuchElementException e)
  • ElementNotVisibleException − 如果 Web 元素不可见但在 DOM 中存在,则会发生此异常。它是 ElementNotInteractable 类的子类。在驱动程序尝试对不可见或隐藏的元素执行操作的场景中,会抛出此异常。在此,如果具有属性名称 tutorial-test 的元素被隐藏,则会发生此异常。

driver.findElement(By.name("tutorial-test")).click();
//Exception Handling:
try {
   driver.findElement(By.name("tutorial-test")).click();
} catch (ElementNotVisibleException e)
  • StaleElementException - 如果 Web 元素不存在,因为它已被删除或不再附加到 DOM,则会发生此异常。此异常与 ElementNotVisibleException 有细微的差别。

    在一些情况下,页面上成功创建了一个特定的 Web 元素,但是目前它可能由于 DOM 刷新、添加了新的导航页面或切换到框架或窗口而缺失。

更新于:2020年6月10日

213 次查看

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.