About this lesson
Count table rows and columns in Selenium Java
Learn Selenium JavaAdvancedTables
How it works
Counting is findElements() plus size(). The question is what to count. Data rows are the tr elements inside tbody; columns are the th cells of the header row, or the td cells of any one data row.
Where you search changes the answer. On the employee table, tr elements under the whole table include the header row, so that count is one higher than the number of data rows. Searching tr across the whole page also picks up the second table's rows.
A CSS selector can do the scoping in one step: #employeeTable tbody tr matches only the data rows of this table.
About the assignment
The starter finds the employee table. You count its data rows and its columns and print both counts, choosing the elements so that the header row is not counted as data.
What you will do
- Find the table's
tbody, then callfindElements()on it fortrelements, and print the list's size after the labelData rows:. - Count the table's
thcells the same way and print the size after the labelColumns:.
Common mistakes
Counting tr under the table
The header row is a
trtoo, so the data row count comes out one too high.Counting from the driver
Rows and headers from
dynamicTableare added in, so both counts are too high.Counting td across the whole table for columns
That gives rows times columns, not the number of columns. Count the cells of one row.
In a real test suite
Row counts check search results, pagination ("25 per page") and filters ("only Engineering rows"). After adding or deleting a record, a test often compares the count before and after.
Lesson 65 read single cells. Lesson 67 loops over the rows and reads cells from each one.
Related lessons
- Read Table Headers with findElements()The header cells that give the column count.
- Iterate All Table DataLoop over the rows you just counted.
- CSS Selectors - BasicsCSS selectors such as
#id, which start the scoped selector used here.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Tables");
WebElement table = driver.findElement(By.id("employeeTable"));
// TODO: Count rows in tbody
// TODO: Count columns (th elements)
// TODO: Print both
driver.quit();
}
}