Reading Data from the table is somewhat different from accessing normal elements from the webpages.Because generally developers when develop the html page they provide id,name etc.But for table they don't provide any id, name etc.So we generally go with XPath.
Below Html code is:
<html>
<head>
<title>TableExample</title>
</head>
<body>
<table border="1">
<tbody>
<tr>
<td>hi</td>
<td>hello</td>
</tr>
<tr>
<td>how are you</td>
<td>what are doing</td>
</tr>
</tbody>
</table>
</body>
</html>
We will try to access 2nd row 2nd column.i.e "what are doing".To access the data present in table we are using XPath for that.
Step:1 Set the parent Element(table)
Xpath locators in selenium webdriver always starts with double forward slash"//".So the parent element is <table> tag.
so xpath starts like "//table".
Step :2 Adding child elements.
The element which is immediate to <table> tag is <tbody>tag.
XPath is now "//table/tbody".
Step :3 After <tbody> tag we are having two <tr> tags.<tr> represents rows in the table.So we are trying to access 2nd <tr> tag.
XPath is now will be "//table/tbody/tr[2].
Step:4 After <tr> tags we are having two <td> tags in each <tr> tag.
<td> represent columns.so we want to access 2nd column.
XPath will be "//table/tbody/tr[2]/td[2].
Now we are having the correct xpath.we can use the above xpath to locate cell in the table.
Example:
package tables;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class tableexample2 {
@Test
public void tablexp()
{
WebDriver driver=new FirefoxDriver();
driver.get("file:///C:/Users/nizamuddin/Desktop/tableexample.html");
driver.manage().window().maximize();
String cellvalue=driver.findElement(By.xpath("//table/tbody/tr[2]/td[2]")).getText();
System.out.println(cellvalue);
}
}
Output:
what are doing
PASSED: tablexp
No comments:
Post a Comment