什麼是 Selenium Webdriver 中的陳舊元素引用異常,以及如何修復它?


在使用 Selenium webdriver 時,我們可能會遇到陳舊元素引用異常。我們可以修復 Selenium webdriver 中的陳舊元素引用異常。陳舊一詞表示不再新鮮且已經腐朽。因此,陳舊元素指向的元素不再存在。

在如下情況下可能會出現異常:元素最初在 DOM 中存在,但在文件物件模型 (DOM) 發生修改後,該元素變為陳舊,若我們嘗試訪問此元素,則會丟擲陳舊元素引用異常。

當元素不再存在於 DOM 中或被刪除時,會導致此異常。我們可以透過以下方法來處理此異常:

  • 重新整理頁面並重新驗證。
  • 實現重試方法。

示例 1

為了說明陳舊元素引用異常,實現程式碼。

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();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //application launch
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");

      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));

      //enter text
      l.sendKeys("Selenium");

      //refresh page
      driver.navigate().refresh();

      //again enter text
      l.sendKeys("Selenium");

      //browser quit
      driver.quit();
   }
}

輸出

示例 2

為了修復陳舊元素引用異常,實現程式碼。

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();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //application launch
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");

      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));

      //enter text
      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();
   }
}

輸出

更新時間: 2021 年 11 月 18 日

超過 1000 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告