9v. WebDriver – Handling tables in two ways

Hiya champions! Welcome back to yet another post on handling web elements using Selenium WebDriver. You learn something new every day, talking of which here is what we will be learning today: handling tables with and without using XPath! Let us go back to our Demo Site for a good grasp of the concept.

Tables are like those celebrities that are everywhere. Well, it is time to go and meet our star! Throughout this post, we will be working with the table, “Table For Practice” from the demo site. There will be a lot of scenarios where you might want to check if a particular data is present in a table’s specific cell. So, let us go ahead and hit the bold on the head!

Method 1: Handling tables without using XPath

In “Table For Practice”, we have a table with two rows and two columns. We have another table nested within the first row, second column.

Example:

Let us try to access the first row of the nested table and print the text “Inner Row 1” to console. Since we are not using XPath here, it is going to be a little complicated. But once you master how to locate a cell with one level of nesting, then accessing a much deeper level would be a piece of cake! The first step is to locate the main table using tag name ‘table’. Any locating strategy can be used but usually table rows and columns don’t have an id or name. So the best way of accessing them is by using their corresponding tag names. The second step is to use the obtained web element (table), locate the nested table. And the last step is, with the nested table web element, locate the first row and obtain its text!

Right clicking on required elements and selecting inspect element gives corresponding HTML code snippet which is as below,

  <table class="table table-bordered">         
	<tr>          
		<td>Row 1</td>           
		<td>                 
			<table class="table table-bordered">                    
				<tr>
					<td>Inner Row 1</td>
				</tr>
                <tr>
					<td>Inner Row 2</td>
				</tr>                 
			</table>

Code:

// Locate 'Table For Practice' using tagName
WebElement practiceTable = driver.findElement(By.tagName("table"));
// Locate Inner table using tagName
WebElement innerTable = practiceTable.findElement(By.tagName("table"));
// Locate 'Inner Row 1' using tagName
WebElement innerRow1 = innerTable.findElement(By.tagName("td"));
// Print the first row text to console
System.out.println("Inner table first row text = " + innerRow1.getText());

Method 2: Handling tables with XPath

The first method requires using three web elements to access the required cell. If there are many levels of nesting involved, then the number of commands to locate the element will increase. To ease this, we have XPath to our rescue! Does the word “XPath” ring a bell? If not, refer to Locating Elements by XPath for constructing it in a simple and easy way.

Example:

Let us locate the second row of the nested table and print its contents to the console. Relative path is given as part of the XPath used to locate the required cell of the nested table.

Code:

// Locate 'Inner Row 2' using xPath
WebElement innerRow2 = driver.findElement(By.xpath("//table/tbody/tr[1]/td[2]/table/tbody/tr[2]/td[1]"));

Overall picture

Let us see the code for the methods discussed above in one single piece!

Scenario

  1. Open Firefox browser
  2. Navigate to the demo site (https://chandanachaitanya.github.io/selenium-practice-site/)
  3. Locate ‘Table For Practice’ using tag name
  4. Locate nested table using tag name
  5. Locate the first row of the nested table using tag name
  6. Print the text, ‘Inner Row 1’ to console
  7. Locate the second row of the nested table using XPath
  8. Print the text, ‘Inner Row 2’ to console

JUnit code for this scenario is,

package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandlingTables {
	// Declaring variables
	private WebDriver driver;
	private String baseUrl;

	@Before
	public void setUp() throws Exception {
		// Selenium version 3 beta releases require system property set up
		System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
		// Create a new instance for the class FirefoxDriver
		// that implements WebDriver interface
		driver = new FirefoxDriver();
		// Implicit wait for 5 seconds
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		// Assign the URL to be invoked to a String variable
		baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
	}

	@Test
	public void testPageTitle() throws Exception {
		// Open baseUrl in Firefox browser window
		driver.get(baseUrl);
		// Locate 'Table For Practice' using tagName
		WebElement practiceTable = driver.findElement(By.tagName("table"));
		// Locate Inner table using tagName
		WebElement innerTable = practiceTable.findElement(By.tagName("table"));
		// Locate 'Inner Row 1' using tagName
		WebElement innerRow1 = innerTable.findElement(By.tagName("td"));
		// Print the first row text to console
		System.out.println("Inner table first row text = " + innerRow1.getText());
		
		// Locate 'Inner Row 2' using xPath
		WebElement innerRow2 = driver.findElement(By.xpath("//table/tbody/tr[1]/td[2]/table/tbody/tr[2]/td[1]"));
		System.out.println("Inner table second row text = " + innerRow2.getText());
	} //End of @Test

	@After
	public void tearDown() throws Exception {
		// Close the Firefox browser
		driver.close();
	}
}

Execution Result:

Each line of code is accompanied with self-explanatory comments as well the code is well explained as part of concept covered thus far.

Upon noticing eclipse IDE’s JUnit view, green bar shows that the test case is executed successfully. Console window shows the absence of any errors. It also shows the text of both nested table rows as expected.

Handling tables eclipse output

Any questions? Fire away in the comments section!

See you soon in another post. Have a nice day!

5 Comments

    • Hi Neeta,
      ID on an element is meant to be unique.

      Please provide sample code so that I can suggest a possible solution.

      Thanks

  1. How can we get row and column no for a given text in a web table by providing the given text from console in eclipse

    • Hi Priyanka,

      Please, can you provide more details as I am not sure how this is related to WebDriver and automation?

  2. I like the way each concept is explained. Especially examples and entire code with clear comments at the end. Keep going!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.