chadlei
chadlei

Reputation: 189

Iterate through table rows and print a href text with Python Selenium

My overall goal is to iterate through every tr in this table and go through several td's per tr and print out the text in them.

I've tried going back as far as the body yet still no luck. ideally I would like to just run a forloop through table[@id='aui']/tbody/tr[i]/td[i] where i is the variable in the range(0, sizeOfTable)

ele = driver.find_elements_by_xpath("//body/div[@id='page']/section[@id='content']/div[@class='aui-page-panel']/div[@class='aui-page-panel-inner']/section[@class='aui-page-panel-content']/div[@class='aui-page-panel']/div[@class='aui-page-panel-inner']/section[@class='aui-page-panel-content']/div[@class='module']/div[@id='projects']/div[@class='p-list']/table[@id='aui']/tbody/tr[1]/td[1]")

right now when I run print(ele.text) after creating ele, it just prints out an empty list

this is the html I'm working off of:

Upvotes: 0

Views: 1895

Answers (1)

supputuri
supputuri

Reputation: 14145

Reason for the issue is a wrong XPath. The table has class with aui but not id.

Correct the XPath as below.

  //table[@class='aui']//tr

This should give you a list of rows and then you can iterate through them.

Script: if you want to print the text in the cell then use this.

rows = driver.find_element_by_css_selector("table.auti  tr")
for row in rows:
    # get the hrefs
    columsWithLink = row.find_element_by_xpath(".//td[a]")
    for column in columsWithLink:
        # print column text
        print (column.text)
        # print link href
        print(column.find_element_by_xpath(".//a").get_attribute("href"))

Script: if you just want to print link hrefs then use the below

rows = driver.find_element_by_css_selector("table.auti  tr")
for row in rows:
    # get the hrefs
    links = row.find_element_by_xpath(".//td/a")
    for link in links:
        # print link href
        print(link.get_attribute("href"))

Upvotes: 2

Related Questions