gpt4 book ai didi

java - Selenium StaleElementReferenceException 显式等待

转载 作者:行者123 更新时间:2023-11-30 08:49:32 27 4
gpt4 key购买 nike

在我的 Selenium 测试代码中有几行

  1. 点击一个复选框
  2. 从选择框中选择一个项目
  3. 点击按钮提交表单

这是代码

WebElement selectAllElement = driver.findElement(By.id("filterForm:selectAll"));
if (selectAllElement.isSelected())
{
selectAllElement.click();
}

Select selectLocation = new Select(new WebDriverWait(driver, 30)
.until(ExpectedConditions
.presenceOfElementLocated(By.id("filterForm:selectLocation"))));

selectLocation.selectByVisibleText(location);

WebElement filterButton = driver.findElement(By.id("filterForm:filterButton"));
filterButton.click();

我在尝试检索页面上的 Select 元素时收到了 StaleElementReferenceException,为了尝试解决这个问题,我在这个元素上添加了一个显式等待,如上面的代码所示。

但是,我仍然收到 StaleElementReferenceException

编辑(这些元素的 HTML)

<form id="filterForm" name="filterForm" method="post" action="/UsersJSFMavenApplication/faces/index.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="filterForm" value="filterForm" />
<input id="filterForm:selectAll" type="checkbox" name="filterForm:selectAll" checked="checked" title="allUsers" onclick="mojarra.ab(this,event,'valueChange',0,'filterForm:filterGrid usersForm')" />All users<table id="filterForm:filterGrid">
<tbody>
<tr>
<td><input id="filterForm:userName" type="text" name="filterForm:userName" disabled="disabled" /></td>
<td><select id="filterForm:selectLocation" name="filterForm:selectLocation" size="1" disabled="disabled"> <option value="Keynsham">Keynsham</option>
<option value="London">London</option>
<option value="Silicon Valley">Silicon Valley</option>
</select></td>
<td><input id="filterForm:filterButton" type="submit" name="filterForm:filterButton" value="Filter" disabled="disabled" /></td>
</tr>
</tbody>
</table>
<input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="-8198231560613594227:-8434387391056535341" autocomplete="off" />
</form>

最佳答案

几周前我遇到了类似的问题。仔细阅读可能是个好主意 StaleElementException是第一个。

我的问题是在选择元素和执行某些操作之间进行了异步调用。我的解决方案是将 try catch 包装在 while 循环中,并在抛出异常之前尝试多次单击元素。所以像这样:

     public static void clickElement(By by) throws Exception {
boolean isClicked = false;
int attempts = 0;
while(!isClicked && attempts < 5) {
try {
WebElement element = driver().findElement(by);
element.click();
isClicked = true;
} catch(StaleElementReferenceException e) {
attempts++;
System.out.println("[DEBUG] StaleElementReference exception caught, trying to locate and click element again");
}
}
if(!isClicked) {
throw new Exception("Could not click " + by + ", after 5 attempts");
}
}

关于java - Selenium StaleElementReferenceException 显式等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31379812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com