Marj Marj - 8 days ago 6x
C# Question

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>

I tried this:

string searchResult = DriverContext.Driver.FindElements(By.CssSelector("#MainContent tr[class='datatable'], tr[class='altrow']")).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


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));