Sashaank
Sashaank

Reputation: 964

how to select the second last item from unordered list with selenium

I am working on a selenium project. The website I want to scrape from has an unordered list with class name pagination. this is how the unordered list code looks

<ul class="pagination">
    <li class="a-disabled">←<span class="a-letter-space"></span><span class="a-letter-space"></span>Previous</li>    
    <li class="a-selected"><a href="...">1</a></li>     
    <li class="a-normal"><a href="...">2</a></li>   
    <li class="a-last"><a href="...">Next<span class="a-letter-space"></span><span class="a-letter-space"></span>→</a></li>
</ul>

In this code, I want to select the second last li element. ie. I want to select the li that has a 2 in it.

I tried this code

WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.XPATH, "//ul[@class='pagination']/li[-2]")))

But obviously this does not work. I guess I have to change the -2 to something. not sure how to do that though. How can I achieve this?

Thanks in advance

Upvotes: 0

Views: 3733

Answers (2)

Apps Maven
Apps Maven

Reputation: 1420

I think the best approach will be using xpath with contains function as you want to select the list item which contains 2 in it.

//ul/li[contains(text(),'2')]

You can also mention the class name of ul if your page contains more unordered lists.

//ul[@class='pagination']/li[contains(text(),'2')]

Upvotes: 0

İbrahim Akar
İbrahim Akar

Reputation: 357

You can use the last() feature of xpath.

WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.XPATH, "//ul[@class='pagination']/li[last()-1]")))

Upvotes: 2

Related Questions