For reading a table first we need to access elements within HTML tables. However, a web designer provides sometimes an Id or name attribute to a cell in the table. So we can't use the methods such as by.id,by.name or by.cssSelector(). So in this case, we can use one more element Locator by.xpath() method.
Consider the HTML code below:-
<title> misbah </title>
<table border= 1>
<td> first cell </td>
<td> second cell </td>
<td> third cell </td>
<td> fourth cell </td>
If we want the text of fourth cell of the table then we can use xpath method overe here. To make Xpath here some below rules we followed:
Step 1 - Set the Parent Element :
XPath locators in WebDriver always start with a double forward slash "//" and then followed by the parent element.
Step 2 - Add the child elements:
<tbody> is the child of any table. So that all child elements in Xpath are placed to the right side of the parent separated by one forward slash “/”.
Step 3 - Add Predicates:
In the above table the elements of two <tr> tags are the child of the <tbody> tags.
//table/tbody/tr from this we can access only element of first <tr> and the elements of the tr is known as Siblings.
According to above table if we want to access second row of the table then we provides the predicates like //table/tbody/tr.
Predicates are the numbers in a pair of square brackets “[ ]” that distinguish a child element and it's siblings.
According to above xpath here we are accessing second data of second row at above table.