1

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()]"));
1
  • What about lastRow = driver.find_element(By.XPATH("(//table[1]//tr)[last()]"));. And if you wait a couple of secs before interacting with the element? Maybe it did not load when you try to interact with it. Commented Dec 6, 2022 at 10:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your code worked. How would I go about selecting the first row with XPATH?
Well, this is a new question, but I added the answer here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.