Working with Web Tables Using Selenium
Web tables are a common part of many web applications, often used to display structured data like product listings, order summaries, or user records. In test automation, validating data within these tables is essential. Selenium WebDriver provides several ways to interact with and extract information from web tables efficiently.
Understanding Web Tables
A web table is structured using HTML <table>, <tr> (table row), <th> (table header), and <td> (table data) tags. To automate tasks like verifying data, clicking links, or extracting values, we need to locate and work with these tags.
Locating Table Elements
To begin working with a web table, first identify the table element using locators like id, class, or XPath.
Example:
html
Copy
Edit
<table id="employeeTable">
<tr>
<th>Name</th>
<th>Position</th>
</tr>
<tr>
<td>John</td>
<td>Manager</td>
</tr>
</table>
To access the table:
java
Copy
Edit
WebElement table = driver.findElement(By.id("employeeTable"));
Counting Rows and Columns
To count rows and columns dynamically:
java
Copy
Edit
List<WebElement> rows = table.findElements(By.tagName("tr"));
int rowCount = rows.size();
List<WebElement> columns = rows.get(0).findElements(By.tagName("th"));
int colCount = columns.size();
Reading Table Data
You can loop through the rows and columns to read data:
java
Copy
Edit
for (int i = 1; i < rowCount; i++) {
List<WebElement> cells = rows.get(i).findElements(By.tagName("td"));
for (WebElement cell : cells) {
System.out.println(cell.getText());
}
}
Note: i starts from 1 to skip the header row.
Searching for Specific Data
If you want to find a specific value, say "Manager", you can use:
java
Copy
Edit
for (WebElement row : rows) {
if (row.getText().contains("Manager")) {
System.out.println("Found Manager: " + row.getText());
}
}
Performing Actions
You can also perform actions like clicking a link in a cell:
java
Copy
Edit
WebElement link = table.findElement(By.xpath("//tr[2]/td[1]/a"));
link.click();
Conclusion
Working with web tables in Selenium is straightforward once you understand the HTML structure. By combining locators, loops, and basic logic, you can verify data, count rows and columns, and interact with elements inside tables. This is an essential skill for any Selenium automation tester dealing with data-driven web interfaces.
Learn Selenium Python Training in Hyderabad
Read More:
Writing Your First Selenium Automation Script in Python
Handling Alerts and Pop-ups Using Selenium Python
Automating Login Pages with Selenium Python
Visit our IHub Talent Training Institute
Comments
Post a Comment