Search code examples
pythonpython-3.xseleniumwebdriver

How do I get an element from an HTML table that has an always changing child element number?


I am trying to collect the total number of hours that I worked from each pay period that I worked. I can collect the total number of hours from the "Grand Totals" section, however it seems like that section never has a static child element number and shares class names with another row.

Here is an example:

from the first page, if I copy selector in Chrome, I get:

#TableTimeCard > tbody > tr:nth-child(12) > td:nth-child(3)

However, when I go to the next pay period, I get:

#TableTimeCard > tbody > tr:nth-child(14) > td:nth-child(3)

That "tr:nth-child" number ranges between 4 and however many number of entries I had on my time card.

Here is the snippet of code from the site. I am trying to take in 10.37:

Page screenshot

I've tried grabbing it by that class name but then it just grabs the first number after "Total Hours" in the image. In this case, 0.00. I believe the reason why is because it has the same class name:

screenshot 2

All I need to do is print grand total hours to console. Any ideas?

I am doing print(driver.find_element_by_css_selector("#TableTimeCard > tbody > tr:nth-child(12) > td:nth-child(3)")

Thanks!


Solution

  • Well, you can use find_elements to store all of them, and can iterate like this :-

    hours = find_elements(By.CSS_SELECTOR, "#TableTimeCard > tbody > tr > td:nth-child(3)")
    print(hours[0].text)
    

    or even you can iterate that list as well :-

    for hour in find_elements(By.CSS_SELECTOR, "#TableTimeCard > tbody > tr > td:nth-child(3)"):
        print(hour.text)
    

    Update 1 :

    In case if you just want to grab Total hours value, use this xpath :-

    //td[text()='Grand Totals']/following-sibling::td[4]
    

    in code :

    print(driver.find_element_by_xpath("//td[text()='Grand Totals']/following-sibling::td[4]").text)