Search code examples
pythonseleniumxpath

Selenium how to select last link in a body?


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 ?


Solution

  • To get the last element. Try following xpath.

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