如何在 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();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
JavaScript
PHP