I have such a structure
How does it look visually
I'm trying to get the last item and click on it, but the 4th item is selected.
driver.findElement(By.xpath(("//*[@id=\"page-body\"]/div/div[2]/ul[last()]"))).click();
How do I click on the last item and on 55?
2 Answers 2
When you look up elements using xpath like this:
driver.findElement(By.xpath(("//*[@id=\"page- body\"]/div/div[2]/ul[last()]"))).click();
you basically look up the last ul
element that is
- the only one in your snippet.
- the container for
li
elements that you should actually look for.
So, your code could look like:
driver.findElement(By.xpath("//div[@class='pagination']/ul/li[last()]")).click();
"//div[@class="pagination"]/li[not(contains(@class, 'arrow') and last()])]/a"
Breaking down:
Inside a div with class pagination -> //div[@class="pagination"]
Look for the li without the arrow class -> li[not(contains(@class, 'arrow')
And fetch the last one -> and last()]
Inside this li, look for a link -> /a
Explore related questions
See similar questions with these tags.
[data-qa="page-link"][data-qa-value="55"]
? That way you don't have to build a complicated XPath that could easily go out of date as things move around.[data-qa-rel="last"]
. The point is to rely on useful information not just structure.