Chapter 17_1: Web tables in selenium

In this chapter we will learn about webtables in a webpage and how to handle webpages.Table is a HTML data which is displayed with the help of <table> tag in co-occurrence with the <tr> and <td> tags. These Web tables are basically a group of elements that are logically stored in a row and column format. It is used to form similar information on a web page.tag <tr>defines the row and tag <td> defines the column of the table.

Lets take an example of mercury tours.com website.

Find the table of flight departure from flights section

When we inspect above table we get html code as

Highlighted part shows the whole table containing

Html tags as<tbody> <tr> <td>

In above example html tags can be defined as:

  1. <table> tag defines HTML table.
    2.<tbody> tag defines rows and columns of a table.
    3.<tr> defines rows in an HTML table.
    4.<td/th> defines the column of an HTML table.

Let’s take an example of above table and choose Column 1 of Row 2 which is ‘ blue skies Airline 360’ in above case:

We will use xpath to find ‘blue skies Airline 360’.

By using xpath we get selenium cell of the table

//table//table//table//table//table[1]//tbody[1]//tr[3]//td[2]

Parent element always start with <table>tag

Here <tbody>defines entire table <tr> is the children of <tbody>

[“”] differentiate  child element from its siblings.<tr>defines the 3rd row of a table.<td>defines the required cell from the table.

Complete code:

package testology;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Webtable
 {
public static void main(String[] args) 
{
System.setProperty("webdriver.driver.chromedriver", "chromedriver.exe");
	WebDriver driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.get("http://newtours.demoaut.com/");
	driver.findElement(By.linkText("SIGN-ON")).click();
	WebElement name = driver.findElement(By.name("userName"));
	name.sendKeys("Testology");
// get the webelement corresponding to password (passwordfield)
	WebElement password = driver.findElement(By.name("password"));
	password.sendKeys("Testology12");
// to click on submit button
	WebElement submitbutton =driver.findElement(By.cssSelector
("input[name='login'][value='Login']"));		submitbutton.click();
	WebElement button = driver.findElement(By.cssSelector
("input[type='image'][name='findFlights']"));
	button.click();
String flightdeparture = driver.findElement
(By.xpath("//table//table//table//table//table[1]//tbody[1]//tr[3]//td[2]")).getText();
System.out.println(flightdeparture);
	}
}