Loading...

Unable to proceed to next button when I have 15+ button on same page having different xpath


Unable to proceed to next button when I have 15+ button on same page having different xpath

List<WebElement> alllinks = driver.findElements(By.xpath("//a[text()='Edit']"));
// To print the total number of links
String a[] = new String[alllinks.size()];

try
{
    for (int i = 0; i < alllinks.size(); i++)
    {
        a[i] = alllinks.get(i).getText();
        if (a[i].startsWith("E"))
        {
            System.out.println("clicking on this link::" + driver.findElement(By.linkText(a[i])).getText());
            driver.findElement(By.linkText(a[i])).click();
            driver.findElement(By.xpath("//button[@name='save']")).click();

        } else
        {
            System.out.println("does not starts with E so not clicking");
        }
    }
} catch (StaleElementReferenceException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

When I click on Edit button then it will get click successfully and working for Save button too. But while click on another(next) EDIT button it fails to click on second EDIT button.

Check the attached image having EDIT and Save button.

- - Source

Answers

answered 1 week ago JeffC #1

The problem is that you start by getting all the Edit links on the page, you loop through them, but in the middle of the loop you refetch the Edit link (using By.linkText(a[i])) and only ever get the first one and click on it.

You already fetched all the Edit links, you don't need to refetch anything (and you don't need to verify that the link starts with "E" since that's part of your locator, text()='Edit'.

Also, you can avoid the StaleElementException by refetching the elements on each loop. StaleElementExceptions happen because the page (or a part of the page) reloads and you try to use a variable storing an element reference from before the reload.

Simplified code is below.

By editButtonLocator = By.xpath("//a[text()='Edit']");
List<WebElement> alllinks = driver.findElements(editButtonLocator);
for (int i = 0; i < alllinks.size(); i++)
{
    alllinks.get(i).click();
    driver.findElement(By.xpath("//button[@name='save']")).click();

    // get the list again to avoid StaleElementException
    alllinks = driver.findElements(editButtonLocator);
}

comments powered by Disqus