如何在 Selenium 中避免“StaleElementReferenceException”?
如果 webdriver 嘗試訪問當前 DOM 中不可用或無效的網頁元素,則會丟擲 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(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.google.com/"); // identify element WebElement n = driver.findElement(By.name("q")); n.sendKeys("tutorialspoint"); //page refresh 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(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.google.com/"); // identify element WebElement n = driver.findElement(By.name("q")); n.sendKeys("tutorialspoint"); //try-catch block 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(); } }
輸出
廣告