我已经尝试了所有可用的解决方法
WebDriverWait wait6 = new WebDriverWait(driver, 500);
wait6 .until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//i[@class='material-icons'])[" + j + "]")));
我有一个应用程序,我需要单击所有项目并获取项目名称的文本,我得到了Stale Element Reference Exception。 我试图用不同的方法来解决它,但没有任何效果。
public void page(WebDriver driver, String Filtername) throws InterruptedException {
waitForElementPresent(driver, 60, sidenavbutton);
click(driver, sidenavbutton);
Thread.sleep(2000);
click(driver, viewcopyportfolio);
Thread.sleep(1000);
click(driver, sidenavbutton);
waitForElementPresent(driver, 30, porfoliosheader);
clearText(driver, pagenumtextbox);
Thread.sleep(1000);
setText(driver, pagenumtextbox, Filtername);
Thread.sleep(1000);
List<WebElement> editicons1 = driver.findElements(By.xpath("//i[@class='material-icons']"));
for (int j = 1; j <= editicons1.size(); j++) {
editicons1 = driver.findElements(By.xpath("//i[@class='material-icons']"));
String porfolioName = driver.findElement(By.xpath("(//mat-table//mat-row)[" + j + "]//mat-cell[2]")).getText();
//Added to fix Stale Element Exception
WebElement editicon = driver.findElement(By.xpath("(//i[@class='material-icons'])[" + j + "]"));
//In click method attached code below this will loop for 5 times
click1(driver, editicon, porfolioName + " portfolio edit icon");
Thread.sleep(1000);
waitForElementPresent(driver, 30, buildportfolioheader);
}
}
此代码为click1方法
public void click1(WebDriver driver, WebElement element, String name) throws InterruptedException {
int attempts = 0;
while(attempts < 5) {
try {
element.click();
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
return;
} catch (Exception e) {
attempts++;
Thread.sleep(500);
try {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
return;
} catch (Exception e2) {
Add_Log.info("Not able to click " + name);
Reporter.log("Not able to click " + name);
TestResultStatus.Testfail = true;
Assert.fail("Not able to click " + name);
}
}
}
}
答案 0 :(得分:0)
“ editicons1 = driver.findElements(By.xpath(” // i [@ class ='material-icons']“)));”循环中的这一行看起来好像不是必需的,您只需要初始计数,我看不出有理由重新加载元素列表。
这种等待逻辑的问题是,如果该元素已经存在,它将睡一秒钟,看到该元素在那里,然后继续,根据我所看到的,下一页可以开始加载,然后您的脚本将充满痛苦。
Thread.sleep(1000);
waitForElementPresent(驱动程序,30,buildportfolioheader);
如果该元素尚未在页面上,我将交换显式等待,使其首先出现。原因是元素的存在并没有真正意义,页面可能仍在运动中,因此在显式等待后稍有睡眠(假设这是最后出现的元素之一)该页面)通常会稳定Flakey脚本。
waitForElementPresent(驱动程序,30,buildportfolioheader);
Thread.sleep(1000);