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 ?
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):
-
do yourArray = driver.findElements(By.tag("a"))
-
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
-
The element at the index "myIndex" of "yourArray" will be the element you’re searching for.
To get the last element. Try following xpath
.
link = driver.find_element_by_xpath("(//a)[last()]")
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 ?
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):
-
do
yourArray = driver.findElements(By.tag("a"))
-
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 -
The element at the index "myIndex" of "yourArray" will be the element you’re searching for.
To get the last element. Try following xpath
.
link = driver.find_element_by_xpath("(//a)[last()]")