Home > OS >  How to get the value of a nested td elements using selenium python
How to get the value of a nested td elements using selenium python

Time:07-23

I am trying to get the value of the 3rd <td> tag in each <tr> in the table.

I tried:

math_grade = wait.until(EC.presence_of_element_located((By.TAG_NAME,'./body/div/div[1]/div[5]/div[1]/table/tbody'))).text
print(math_grade)

but it didn't work, knowing that, this table only shows after a search so i added a sleep(5) before this line of code runs.

enter image description here

CodePudding user response:

Try this code to get values from each 3rd cell of each table row

math_grades = [td.text for td in wait.until(EC.presence_of_all_elements_located((By.XPATH,'//tr/td[3]')))]

P.S. Note that to use XPath as locator you need to pass By.XPATH selector type but not By.TAG_NAME

P.P.S. Add HTML-code samples as text, not as image-file

CodePudding user response:

To print the text from the 3rd <td> from each <tr> instead of presence_of_element_located() you need to induce WebDriverWait for the visibility_of_all_elements_located() and using List Comprehension you can use either of the following locator strategies:

  • Using xpath and text attribute:

    print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table/tbody//tr//td[@class='grade']//following-sibling::td[1]")))])
    
  • Using xpath and get_attribute() attribute:

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table/tbody//tr//td[@class='grade']//following-sibling::td[1]")))])
    
  • Related