Click on last row of an HTML table with selenium

Question:

I am trying to click on the last row of a table using python and selenium. I have highlighted what I am trying to click in the HTML code image.

enter image description here

lastRow =  driver.find_element(By.CSS_SELECTOR("td.phone-leftinline yui-dt6-col-Type yui-dt-col-Type yui-dt-first:last-of-type"))
lastRow.click()

This codes keeps throwing an error:

Traceback (most recent call last):
  File "/Users/daniel/Python/main.py", line 42, in <module>
    lastRow =  driver.find_element(By.CSS_SELECTOR("td.phone-leftinline yui-dt6-col-Type yui-dt-col-Type yui-dt-first:last-of-type"))
TypeError: 'str' object is not callable

I have also tried this with no luck:

lastRow =  driver.find_element(By.XPATH("(//table[1]/tbody/tr)[last()]"));
Asked By: Daniel

||

Answers:

You have syntax errors with both expressions you trying to use.
I can’t validate it since you did not share a link to the page you working on, but try the following (fixed syntax of your trials):

driver.find_element(By.CSS_SELECTOR, "td.phone-leftinline.yui-dt6-col-Type.yui-dt-col-Type.yui-dt-first:last-of-type").click()

or

driver.find_element(By.XPATH, "(//table[1]/tbody/tr)[last()]").click()

Additionally you may need to wait for element clickability. WebDriverWait expected_conditions explicit wait element_to_be_clickable is normally used for that.
UPD
Additionally to last() XPath supports indexing elements so that you can select first, second, n-th element, as following:
This will select the first element

driver.find_element(By.XPATH, "(//table[1]/tbody/tr)[1]").click()

This will select the second

driver.find_element(By.XPATH, "(//table[1]/tbody/tr)[2]").click()

etc.
Pay attention: In XPath indexation starts with 1, not with 0 as in most other places.

Answered By: Prophet