stack
stack

Reputation: 17

Loop through table rows and print text in selenium using python

I have an HTML Table:

<div class="report-data">
  <table>
    <thead>
      <tr>
        <td></td>
        <td>All</td>
        <td>Long</td>
        <td>Short</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Net Profit</td>
        <td>
          <div>3644.65</div>
          <div><span class="additional_percent_value">3.64&nbsp;%</span></div>
        </td>
        <td>
          <div>3713.90</div>
          <div><span class="additional_percent_value">3.71&nbsp;%</span></div>
        </td>
        <td>
          <div><span class="neg">69.25</span></div>
          <div><span class="additional_percent_value"><span class="neg">0.07&nbsp;%</span></span>
          </div>
        </td>
      </tr>
      <tr>
        <td>Net Profit</td>
        <td>
          <div>3644.65</div>
          <div><span class="additional_percent_value">3.64&nbsp;%</span></div>
        </td>
        <td>
          <div>3713.90</div>
          <div><span class="additional_percent_value">3.71&nbsp;%</span></div>
        </td>
        <td>
          <div><span class="neg">69.25</span></div>
          <div><span class="additional_percent_value"><span class="neg">0.07&nbsp;%</span></span>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>

Now I want to print all the td[1] values for each row, so My output should be:

Net Profit

Net Profit

So I executed the below code:

    for dt in driver.find_element_by_xpath("//div[@class='report-data']/following-sibling::table/tbody/tr"):
        text_label = dt.find_element_by_xpath(".//td").text
        print(text_label)

But it throws error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='report-data']/following-sibling::table/tbody/tr"}

Upvotes: 1

Views: 1061

Answers (1)

Jack Fleeting
Jack Fleeting

Reputation: 24940

You're almost there, I believe. Try this:

content = driver.find_elements_by_xpath("//div[@class='report-data']/table/tbody/tr")
for dt in content:
    text_label = dt.find_element_by_xpath("./td").text
    print(text_label)

Upvotes: 1

Related Questions