Selenium WebDriver StaleElementReferenceException。


我們在 Selenium WebDriver 中遇到了 **StaleElementReferenceException**。顧名思義,“stale”是陳舊的意思。可能出現 DOM 中以前存在的元素現在因 DOM 中的修改而不再可用的情況。

在這種情況下,如果我們嘗試訪問該元素,則會引發 StaleElementReferenceException。由於以下原因,遇到了此類異常 -

  • 元素不再存在於 DOM 中。

  • 元素已被完全刪除。

如下所述,我們可以防止 StaleElementReferenceException 的某些方法 -

我們可以重新載入網頁並嘗試與相同的元素進行互動。

driver.navigate().refresh();
driver.findElement(By.id("txt")).sendKeys("Selenium");

我們可以新增 try 捕獲塊並與相同的元素進行互動。對於迴圈,將有五次嘗試。如果在五次嘗試之前識別出該元素,則應退出迴圈。

for(int k=0; k<=5;k++){
   try{
      driver.findElement(By.id("txt")).sendKeys("Selenium");
      break;
   }
   catch(Exception exp){
      System.out.println(exp.message());
   }
}

為防止 StaleElementReferenceException,我們可以新增顯式等待[同步],藉助預期條件 presenceOfElementLocated 來等待元素在 DOM 中呈現。

w.until(ExpectedConditions.presenceOfElementLocated(By.name("presence")));

更新於:2020 年 10 月 26 日

720 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.