0

I have such a structure

enter image description here

How does it look visually

enter image description here

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?

  • Why don't you put some attributes on those elements to make them easier to target? – jonrsharpe Mar 24 at 12:26
  • @jonrsharpe I do not understand what you're talking about( – Temp13 Mar 24 at 12:32
  • Well you're trying to click on a link to page 55, how much easier would that be with e.g. [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. – jonrsharpe Mar 24 at 12:33
  • @jonrsharpe What if tomorrow number will be 256? – Temp13 Mar 24 at 12:34
  • You can put other attributes on too, if you want something to tell you it's the last one that's fine. E.g. [data-qa-rel="last"]. The point is to rely on useful information not just structure. – jonrsharpe Mar 24 at 12:35
0

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

  1. the only one in your snippet.
  2. 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();
0
"//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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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