Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selenium count elements of xpath

i have a webpage with a table containing many Download links i want to let selenium click on the last one :

table:

item1 Download
item2 Download
item3 Download

selenium must click on Download next item3

i used xpath to find all elments then get size of returned array or dict in this way

x = bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]").size()

but i get always this error

TypeError: 'dict' object is not callable

i tried to use get_xpath_count methode but the methode doen't exist in selenium in python!

i thought about another solution but i don't know how to do it and it is as following

x = bot._driver.find_element_by_xpath("(//a[contains(text(),'Download')])[size()-1]")

or

x = bot._driver.find_element_by_xpath("(//a[contains(text(),'Download')])[last()]")

or something else

like image 871
Ben Ishak Avatar asked Oct 21 '22 02:10

Ben Ishak


2 Answers

Use find_elements_by_xpath to get number of relevant elements

count = len(driver.find_elements_by_xpath(xpath))

Then click on the last element:

elem = driver.find_element_by_xpath(xpath[count])
elem.click()

Notice: the find_elements_by_xpath is plural in first code snippet

like image 141
Shane Avatar answered Oct 27 '22 23:10

Shane


Although get_xpath_count("Xpath_Expression") does not exist in Python, you can use

len(bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]"))

to achieve the number of elements, and then iterate through then, using

something.xpath(//a[position()=n])

where

n < len(bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]"))

like image 20
Lucas Ribeiro Avatar answered Oct 27 '22 22:10

Lucas Ribeiro