Selenium how to select last link in a body?

Question:

I have a html page like below

<body>
    
    <div>
        <a class="btn btn-info" href="a.php">A</a>
        <a class="btn btn-info" href="b.php">B</a>
        <a class="btn btn-info" href="c.php">C</a>
        <a class="btn btn-info" href="d.php">D</a>
    </div>
        
    <a class="btn btn-info" href="f.php">F</a>

</body>

I need to select last link F. I have tried like below

link = driver.find_element_by_xpath("//a[last()]")

It’s selecting D

I also tried below way

email = driver.find_element_by_xpath("/body//a[last()]")

In this time unable to locate element. How can I get last link here in an easy way ?

Asked By: Niloy Rony

||

Answers:

use the driver.findElements() method and put the return value in an array.

The last link will be the last element of the array.

I suggest you to (for various reasons):

  1. do yourArray = driver.findElements(By.tag("a"))

  2. for every element check if the href attribute is not null with element.getAttribute("href") != null and update a myIndex var if it’s not

  3. The element at the index "myIndex" of "yourArray" will be the element you’re searching for.

Answered By: user12196313

To get the last element. Try following xpath.

link = driver.find_element_by_xpath("(//a)[last()]")
Answered By: KunduK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.