Home > Back-end >  Get all tds from a tr with Selenium
Get all tds from a tr with Selenium

Time:09-21

I am trying to automate a process with Selenium but I am a bit stuck, I explain what I want to do:

  1. I find a td with specific text inside (done)
  2. From that td, I get its tr looking for xpath in it (done).
  3. Now, inside that tr, there are 12 td, I want to get the penultimate one, but I don't know how to do it anymore.

This is the code of what I comment:

td = WebDriverWait(driver, 180).until(
            EC.element_to_be_clickable((By.XPATH, f'//td[text()="{profile}"]')))
tr = td.find_element_by_xpath("../..")

I have tried the following, but it doesn't work for me:

# this
td_11 = tr.find_element_by_xpath(".//td[11]")
# this
td_11 = td.find_element_by_xpath('../..').find_element_by_xpath(".//td[2]")
# and this
td_11 = tr.find_elements_by_tag_name("td") # then get the 11

but i can't get the td i want ...

The structure of the tr is as follows:

<tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
</tr>

CodePudding user response:

to get to the td's which are in tr and if this represent the tr

tr = td.find_element_by_xpath("../..")

you could do :

all_tds = tr.find_elements_by_xpath(".//child::td")

this would represent all the td's that you've inside tr.

Now to go to penultimate , I do not know how does it look like in HTML. but if it is an attribute then you can try with below code :

penultimate_td = tr.find_element_by_xpath(".//child::td[@penultimate]")

basically I need to see the HTML for penultimate to give you reliable locator.

or since you have all_tds which is a list in Python, you can iterate that as well to get the each web element.

  • Related