0

我已经尝试了所有可用的解决方案

WebDriverWait wait6 = new WebDriverWait(driver, 500);       
wait6 .until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//i[@class='material-icons'])[" + j + "]")));

我有应用程序,我需要单击所有项目并获取项目名称的文本我得到过时的元素引用异常。我试图用不同的方法来解决它,但没有任何效果。

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);
        }
    }

        }
}
4

1 回答 1

1

" editicons1 = driver.findElements(By.xpath("//i[@class='material-icons']"));" 循环中的这一行看起来不需要它,您只需要初始计数,我看不出重新加载元素列表的理由。

这个等待逻辑的问题是,如果元素已经存在,它只会休眠一秒钟,看到元素在那里然后继续,从我所看到的,下一页可以开始加载,然后你的脚本将在一个受伤的世界里。

线程.sleep(1000);

waitForElementPresent(驱动程序,30,buildportfolioheader);

如果该元素尚未在页面上,我将交换显式等待以先出现。原因是一个元素的存在并不意味着很多,页面可能仍然在运动,所以在显式等待之后有点睡眠(假设这是最后出现的元素之一页面)通常会稳定 flakey 脚本。

waitForElementPresent(驱动程序,30,buildportfolioheader);

线程.sleep(1000);

于 2019-01-02T20:00:11.703 回答