如何解决 Selenium WebDriver 中的过时元素引用异常?


我们可以解决 Selenium webdriver 中的过时元素引用异常。术语过时表示某些不再新鲜且已腐烂的东西。因此,过时元素指向不再存在的元素。

可能有这样的情况,元素最初存在于 DOM 中,但在文档对象模型 (DOM) 中进行修改后,元素变为过时,并且当我们尝试访问这个元素时,会抛出过时元素引用异常。

无论何时元素不存在于 DOM 中或被删除,都会导致此异常。我们可以通过以下方法处理此异常 -

  • 刷新页面并重新验证。

  • 实施重试方法。

示例

代码实现来说明过时元素异常。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class StaleElmnt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l = driver.findElement(By.id("gsc−i−id1"));
      l.sendKeys("Selenium");
      //refresh page
      driver.navigate().refresh();
      l.sendKeys("Selenium");
      driver.quit();
   }
}

输出

示例

代码实现来修复过时元素异常。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.StaleElementReferenceException;
public class StaleElmntFix{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l = driver.findElement(By.id("gsc−i−id1"));
      l.sendKeys("Selenium");
      //refresh page
      driver.navigate().refresh();
      //fix exception with try−catch block
      try{
         l.sendKeys("Selenium");
      }
      catch(StaleElementReferenceException e){
         l = driver.findElement(By.id("gsc−i−id1"));
         l.sendKeys("Selenium");
         //obtain value entered
         String s= l.getAttribute("value");
         System.out.println("Value entered is: " +s);
      }
      driver.quit();
   }
}

输出

更新时间: 01-Feb-2021

6K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始使用
广告
© . All rights reserved.