top of page

Selenium C# Tutorial: Locating table rows and cells

Updated: Mar 5

DHTML tables contain data that should be displayed in a specific logical order to the end-user. Selenium WebDriver supports this web Element with methods that allow us to locate the rows and cells effectively by using a set of the By class methods.

The code examples in this article are based on the following HTML code:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 5px;
  text-align: left;    
}
</style>
</head>
<body>

<h2>Cell that spans two columns</h2>
<p>To make a cell span more than one column, use the colspan attribute.</p>

<table style="width:30%">
  <tr>
    <th>Name</th>
    <th colspan="2">Math Test Score</th>
  </tr>
  <tr>
    <td>Bill</td>
    <td>70</td>    
  </tr>
  <tr>
    <td>Dan</td>
    <td>55</td>    
  </tr>
  <tr>
    <td>Stef</td>
    <td>90</td>   
  </tr>
</table>

</body>
</html>

How it works...

A table in HTML is a collection of rows <tr>, headers<th> and columns <td>, each <tr> element is the root of one or more columns <td>.

  • < table > – Defines an HTML table

  • < th > – Contains header information in a table

  • < tr > – Defines a row in a table

  • < td > – Defines a column in a table

Before using the table element, we should first identify it as an element similar to any other element in HTML (e.g., checkbox, Radio-button, etc.).



Example no'1: Extract all data from a table using rows(tr)

The following code will go through each row and print the associated values (Each column value is printed per iteration).


Note: Each <tr> element then holds the <td> elements, which are the columns or cells of the table. The test iterates through the row and columns to print the data.


Code:

static void Main(string[] args)
        {
            IWebDriver chromedriver = new ChromeDriver();           
            string siteToAccess = "file:///C:/Users/home-pc3/Desktop/checkbox%20Example.html";
            GotoSite(chromedriver, siteToAccess);

            IWebElement tempElement;

            //Locating table as a WebElement 
            tempElement = chromedriver.FindElement(By.CssSelector("body > table:nth-child(3) > tbody:nth-child(1)"));

            //TagName strategy is used to get all <tr> elements
            IList<IWebElement> ListOfElements = tempElement.FindElements(By.TagName("tr"));
            foreach (var item in ListOfElements)
            {
                Console.WriteLine(item.Text);
            }
        }

        private static void GotoSite(IWebDriver chromedriver, string siteToAccess)
        {
            chromedriver.Navigate().GoToUrl(siteToAccess);
            Thread.Sleep(6000);
        }

Result:

Example no'2: Extract all data from a table using rows(td)

We will use the same code of example 1, but with a single change in the find. elements method:

 //TagName strategy is used to get all <td> elements
            IList<IWebElement> ListOfElements = tempElement.FindElements(By.TagName("td"));
            foreach (var item in ListOfElements)
            {
                Console.WriteLine(item.Text);
            }

Result:












Example no'3: Count the number of rows and columns

//The Numbrt of rows 
IList<IWebElement> ListOfElements = tempElement.FindElements(By.TagName("tr"));
Console.WriteLine(ListOfElements.Count);

//The Number of columns
ListOfElements = tempElement.FindElements(By.TagName("th"));
Console.WriteLine(ListOfElements.Count);



Example no'4: Locating value in a specific cell

//Locating a specific cell using CSS selector 
tempElement = chromedriver.FindElement(By.CssSelector("body > table:nth-child(3) > tbody:nth-child(1) > tr:nth-child(1) > th:nth-child(2)"));
Console.WriteLine(tempElement.Text);

Locating child elements on a table

Until now, we worked with simple tables that allow us to perform all operations without any significant challenges. However, in some projects, you will face tables that possess chilled elements dynamically created based on user operations. Therefore we will need to use advanced strategies to locate chilled elements using XPath and CSS.

To demonstrate the code examples, we will use the following HTML table:

<!DOCTYPE html><html><head><title>Locating child elements</title></head> <body><table border="1" width="50%">
<tr> <td>UserID_1 </td>
<td><a href="mailto:X@mail.com">user_1@mail.com</a></td> <td><div> 
<label for="TMPID_Premium Contract">Premium Contract</label> 
<input type="checkbox" id=" TMPID1 _Premium Contract" checked="true"/>
 <label for=" TMPID _Basic Contract">Basic Contract</label> 
<input type="checkbox" id=" TMPID1 _Basic Contract" />  </div> </td> </tr>

 <tr> <td>UserID_2 </td>
<td><a href="mailto:Y@mail.com">user_2@mail.com</a></td> <td><div> 
<label for="SeleniumWebDriver_Premium Contract">Premium Contract</label> 
<input type="checkbox" id=" TMPID2 _Premium Contract" "/> 
<label for=" TMPID _Basic Contract">Basic Contract</label> 
<input type="checkbox" id=" TMPID2 _Basic Contract" checked="true"/>
 </div> </td> </tr> </table></body></html>

As you can see from the HTML snippet, the user ID is not static, and therefore we cannot use the regular locator strategies (The ID attribute cannot be associated with a user). To overcome this issue, we can use the XPath and CSS selectors in the following way:


Code Example:

1. Checkbox validation (if/else).

2. We will remove the "Premium Contract" checkbox.

3. We will check the "Basic Contract" checkbox.

4. We will validate that the "Basic Contract" is checked.


XPath

Checkbox = Firefox.FindElement(By.XPath("//td[contains(text(),'UserID_1')]/following-sibling::td/descendant::div/label [contains(text(),'Premium')]/following-sibling::input"));
if (Checkbox.Selected == true)
{Checkbox.Click();}
else{//Do something}

Checkbox =Firefox.FindElement(By.XPath("//td[contains(text(),'UserID_1')]/following-sibling::td/descendant::div/label [contains(text(),'Basic')]/following-sibling::input"));
Checkbox.Click();
Assert.IsTrue(Checkbox.Selected);

CSS

We can perform the same task with the CSS selector using the following syntax:

Checkbox = Firefox.FindElement(By.CssSelector("td:contains('UserID_1')+td+td>div>label:contains ('Premium')+input"));

It may seem complicated so let’s break it into small pieces:

"td:contains('UserID_1') = identify the requested user.

"