How to Handle Web Tables in Selenium WebDriver
How to Handle Web Tables in Selenium WebDriver
🧾 What is a Web Table?
A web table is an HTML structure used to display data in rows and columns, typically defined using <table>, <tr> (table row), <th> (table header), and <td> (table data) tags.
✅ Steps to Handle Web Tables in Selenium
🔹 1. Locate the Table
You can locate the whole table using any of Selenium's locator strategies (e.g., id, xpath, cssSelector).
java
Copy
Edit
WebElement table = driver.findElement(By.id("tableId"));
🔹 2. Get All Rows
Rows are usually marked with <tr> tags.
java
Copy
Edit
List<WebElement> allRows = table.findElements(By.tagName("tr"));
System.out.println("Total rows: " + allRows.size());
🔹 3. Get All Columns (from a specific row)
Assuming you want columns from the first row:
java
Copy
Edit
List<WebElement> allColumns = allRows.get(0).findElements(By.tagName("td"));
System.out.println("Total columns in first row: " + allColumns.size());
🔹 4. Loop Through All Data
To read all data from the table:
java
Copy
Edit
for (WebElement row : allRows) {
List<WebElement> columns = row.findElements(By.tagName("td"));
for (WebElement cell : columns) {
System.out.print(cell.getText() + "\t");
}
System.out.println();
}
📌 Example Table HTML
html
Copy
Edit
<table id="exampleTable">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
</tr>
<tr>
<td>Bob</td>
<td>25</td>
</tr>
</table>
⚙️ Useful Tips
Use XPath or CSS selectors to target specific cells:
java
Copy
Edit
WebElement cell = driver.findElement(By.xpath("//table[@id='exampleTable']/tbody/tr[2]/td[1]"));
System.out.println("Cell value: " + cell.getText());
To handle dynamic tables, wait for them to load using WebDriverWait.
🧠Common Use Cases
Reading data from tables (e.g., order lists, reports)
Verifying specific cell values
Clicking buttons or links inside table cells
Learn Selenium JAVA Training in Hyderabad
Read More
Handling Dropdowns and Multiple Windows in Selenium
Using TestNG with Selenium: Why and How
Top 10 Selenium WebDriver Commands Every Beginner Should Know
Understanding XPath and CSS Selectors in Selenium
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment