-1

How to know what is the last xpath value on an element?? How can we count the number of elements present with this xpath value which just differs with li [ Values ] ??

driver.findElement(By.xpath(".//*[@id='name']/div/div[2]/fieldset/div[47]/ul/li["+i+"]/div/div[2]/div/div[2]/div[5]/span[1]/span[1]/span"));

Here i starts with 0 , and if max i value =6 then how to get that the last xpath value of the element has i value=6??

3 Answers 3

2

Personally I wouldn't go with the xpath but instead create a list of the WebElements via driver.getElements(By.tagName("li")) but if you're hellbend on using xpaths you could use a simple try catch structure to see if the current element exists and let it return the last existing path. I'd try something along the lines of

static String getLastElement(){
    String LastValidPath = "";
    String xpathstart= ".//*[@id='name']/div/div[2]/fieldset/div[47]/ul/li[";
    String xpathEnd="]/div/div[2]/div/div[2]/div[5]/span[1]/span[1]/span"))";
    int value = 0;
    Boolean found = false;
    while(found == false){
        String CurrentXpath = (xpathStart + value + xpathEnd);
        try{
            driver.findElement(By.xpath(CurrentXpath));
            LastValidPath = CurrentXpath;
        }catch(NoSuchElementException e){
            found = true;
        }
    }
    return LastValidPath;
}

This function looks up the given path and saves it as LastValidPath if the Path exists, if the Path doesn´t exist it throws a NoSuchElementException, breaks out of the loop and returns the last Path that existed.

1
  • +1 for "hellbend" :-) My advise about how to use XPath would be "don't, if you can work around it". Jun 28, 2016 at 14:18
0

There is an XPath function called Last().

So try something along the lines of:

.//*[@id='name']/div/div[2]/fieldset/div[47]/ul/li[last()]/div/div[2]/div/div[2]/div[5]/span1/span1/span"

Note: you might have to put the entire first section (including the li) in parentheses.

0

If you really need to count the number of elements (or get the index of the last one)...

Instead of findElement(), use findElements() to find all of the li elements. That returns a list. The size of the list tells you how many there are.

If you don't really need the index, but need only to retrieve the last one, try FDM's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.