Get table row text python selenium

时间秒杀一切 提交于 2020-03-23 07:35:40

问题


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.


回答1:


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
    



回答2:


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)


来源:https://stackoverflow.com/questions/56323436/get-table-row-text-python-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!