如何在 Selenium 中避免"StaleElementReferenceException"?

seleniumautomation testingtesting tools

如果 Web 驱动程序尝试访问 DOM 中当前不可用或无效的 Web 元素,则会抛出 StaleElementReferenceException。

这可能是由于页面刷新、元素被意外删除、修改或不再连接到 DOM 造成的。可以通过以下技术避免此类异常 −

  • 页面刷新。

  • 使用重试机制。

  • 使用 try-catch 块。

  • 等待某些预期条件(例如 presenceOfElementLocated)或在获取元素的过时条件时刷新页面。

示例

出现 StaleElementException 的代码实现

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 StaleElemntExc{
   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);
      //URL 启动
      driver.get("https://www.google.com/");
      // 识别元素
      WebElement n = driver.findElement(By.name("q"));
      n.sendKeys("tutorialspoint");
      //页面刷新
      driver.navigate().refresh();
      n.sendKeys("Java");
      driver.close();
   }
}

输出

避免 StaleElementException 的代码实现。

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 StaleElmntAvoid{
   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);
      //URL 启动
      driver.get("https://www.google.com/");
      // 识别元素
      WebElement n = driver.findElement(By.name("q"));
      n.sendKeys("tutorialspoint");
      //try-catch 块
      try{
         n.sendKeys("Java");
      }
      catch(StaleElementReferenceException exp){
         n = driver.findElement(By.name("q"));
         n.sendKeys("Java");
         String v= n.getAttribute("value");
         System.out.println("Text is: " +v);
      }
      driver.close();
   }
}

输出


相关文章