Marj
Marj

Reputation: 312

How to extract row data from HTML table and convert to text for Selenium and c#

I am new to selenium and c#,then I encountered an HTML table which is below:

<table class="datatable" id="MainContent">
   <tr class = "headerRow">
     <tr class = "datatable">
      <td class="hiddenColumn">1</td>
      <td style="width:20%;">Test 1</td>
     <tr class = "altrow">
      <td class="hiddenColumn">2</td>
      <td style="width:20%;">Test 2</td>
</table>

I tried this:

    string searchResult = DriverContext.Driver.FindElements(By.CssSelector("#MainContent tr[class='datatable'], tr[class='altrow']")).ToString();
Console.WriteLine(searchResult.ToString());

I am unable to display the contents of datatable and altrow in text. What is the best approach for this, as I would also want to compare the text values to our database

Upvotes: 0

Views: 518

Answers (1)

Buaban
Buaban

Reputation: 5137

The FindElements() method returns a collection of WebElements. Then you can access text of each element by the property Text. So the code should be like this:

var elements = DriverContext.Driver.FindElements(By.CssSelector("#MainContent tr.datatable,#MainContent tr.altrow")).ToList();
elements.ForEach(e => Console.WriteLine(e.Text));

Upvotes: 2

Related Questions