Andre_k
Andre_k

Reputation: 1740

Get table row text python selenium

This is the html

<table id="dataLstSubCat" cellspacing="0" style="border-collapse:collapse;">
    <tbody><tr>
        <td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_0" href="javascript:__doPostBack('dataLstSubCat$ctl00$LnkBtnSubCat','')">Primers</a>
                      </td><td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_1" href="javascript:__doPostBack('dataLstSubCat$ctl01$LnkBtnSubCat','')">Intermediates</a>
                      </td><td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_2" href="javascript:__doPostBack('dataLstSubCat$ctl02$LnkBtnSubCat','')">Finishes</a>
                      </td>
    </tr>
</tbody></table>

Now I want to extract the table data(td) text like I want to extract the text

[Primers,Intermediates,Finishes]

This is what I have tried

new_text=driver.find_element_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr"))
new_text.text

which gives o/p in string and not in list

Primers Intermediates Finishes

Is there any way by which it can be done.

Upvotes: 2

Views: 4677

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193308

To extract the table data [Primers,Intermediates,Finishes] you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print([my_text_elem.get_attribute("innerHTML") for my_text_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table#dataLstSubCat>tbody>tr td>a")))])
    
  • Using XPATH:

    print([my_text_elem.get_attribute("innerHTML") for my_text_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='dataLstSubCat']/tbody/tr//td/a")))])
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Upvotes: 1

Robert
Robert

Reputation: 171

One option is to use find_elements_by_xpath and then with for loop add it to the list like:

list = []
new_text=driver.find_elements_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr/td"))
for text in new_text:
   list.append(text.text)

Upvotes: 1

Related Questions