如何解決 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.tw/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.tw/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+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始使用
廣告