Selenium find last element with specific class name in div Java

I am testing a page with the following structure with Selenium in Java:

<div class="pagination">
  <ul class="pagination__list">

    <li class="pagination__item pagination__item--prev pagination__item--disabled">
    </li> 

    <li class="pagination__item pagination__item--active">
      1
    </li>
    <li class="pagination__item">
      2
    </li>
    ...
    <li class="pagination__item">
        6
    </li>
    <li class="pagination__item">
        7
    </li> 
    <li class="pagination__item pagination__item--next">
    </li>
  </ul>
</div>

My goal is to find the last li element with the class "pagination__item" in the ul, but not the one that also has the class "pagination__item--next". So basically I am trying to find the li with 7 inside of it using XPath.

I have tried the following codes but they didn't work because "The string is not a valid XPath expression."

  1. driver.findElement(By.xpath("(.//div[@class=\"pagination\"]/li[@class=\"pagination__item\")[last()]"));

  2. driver.findElement(By.xpath(".//div[@class=\"pagination\"]/li[@class=\"pagination__item\" and last()]/");

2 answers

  • answered 2021-05-03 17:53 Prophet

    The element you are looking for can be located with the following xpath: (//li[@class='pagination__item'])[last()]

  • answered 2021-05-03 17:53 vitaliis

    With css selector:

    driver.find_element_by_css_selector(".pagination__list>.pagination__item:last-of-type")
    

    Or just .pagination__item:last-of-type if you do not need your locator to be linked to parent element.