5

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

Sqeaky
  • 1,876
  • 3
  • 21
  • 40
Ben Ishak
  • 669
  • 3
  • 11
  • 27
  • Can you print the result of `bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]")`? –  Aug 20 '13 at 20:02
  • 1
    [size](https://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webelement.WebElement.size) is a property. If you want to find all items matching your `xpath` use `find_elements_by_xpath` (note the `s`). – Maciej Gol Aug 20 '13 at 20:05
  • 2
    @kroolik, yeah it works now with "s" but it returns an empty list, `size()` doesn't work but `len(x)` works. in another hand `bot._driver.find_element_by_xpath("(//a[contains(text(),'Download')])[5]").click()` ***without "s"*** works! so why does `find_elements_by_xpath` returns empty list :/ – Ben Ishak Aug 20 '13 at 20:46

3 Answers3

2

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

Shane
  • 691
  • 1
  • 6
  • 12
1

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')]"))

Nima Soroush
  • 12,242
  • 4
  • 52
  • 53
Lucas Ribeiro
  • 6,132
  • 2
  • 25
  • 28
0

the best way to do this is to use JavaScript and find elements by class name

self.bot._driver.execute_script("var e = document.getElementsByClassName('download'); e[e.length-1].click()")

source: http://de.slideshare.net/adamchristian/javascript-testing-via-selenium

Ben Ishak
  • 669
  • 3
  • 11
  • 27