当我进行 selenium 测试时,我在网站上测试某些 ajax 功能时遇到了问题。我收到错误 Exception in thread "main"org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
。
在查找了一堆东西之后,我知道我收到此错误的原因是因为我在第一个选择对象中访问的元素被认为是因为 ajax 重新加载了网站的该部分。
为了绕过这个异常,我每次都创建一个新的选择对象。重新加载页面时,xpath 不会更改。
是否可以只使用对象的新 xpath 刷新 Select,而不是每次都创建一个新的?
感谢您的帮助。
public static boolean ajaxFunctionalityFF() throws InterruptedException {
int rowCount=driver.findElements(By.xpath("//table[@class='classname']/tbody/tr")).size();
rowSizes.add(rowCount);
Select ajaxSelector = new Select(driver.findElement(By.id("edit-term")));
ajaxSelector.selectByVisibleText("-Beef);
Thread.sleep(4000);
rowCount=driver.findElements(By.xpath("//table[@class='classname']/tbody/tr")).size();
rowSizes.add(rowCount);
totalElements = totalElements + rowCount;
Select ajaxSelector2 = new Select(driver.findElement(By.id("edit-term"))); //create a new one to fix the stale element exception
ajaxSelector2.selectByVisibleText("-Cattle");
Thread.sleep(4000);
rowCount=driver.findElements(By.xpath("//table[@class='classname']/tbody/tr")).size();
最佳答案
每次刷新 HTML 的该部分时,您都需要获取它。我会做类似的事情
private By selectLocator = By.id("edit-term");
public static boolean ajaxFunctionalityFF() throws InterruptedException
{
...
Select ajaxSelector = getSelect();
...
ajaxSelector = getSelect();
ajaxSelector.selectByVisibleText("-Cattle");
...
}
public static Select getSelect()
{
return new Select(driver.findElement(selectLocator));
}
关于java - 测试ajax时是否可以刷新Selenium中的Select对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612619/