About this lesson
Get a table cell value in Selenium Java by the cell's id
Learn Selenium JavaAdvancedTables
How it works
When cells have ids, reading one is a plain driver.findElement(By.id("emp2Age")) followed by getText(). The employee table on the Tables page gives every cell an id built from the row number and the column: emp2Name, emp5Dept, emp1Salary. That pattern lets a test compute the id it needs instead of walking the table.
getText() returns the cell exactly as displayed, with formatting. Salaries come back with the dollar sign and the thousands comma, so they are text, not numbers. Strip the symbols before converting if you need arithmetic.
Without ids, the same cell is reached by position, for example By.xpath("//table[@id='employeeTable']/tbody/tr[2]/td[1]") for the second row's name. Position-based locators break when rows are sorted or columns move, which is why ids are preferred when the app provides them.
About the assignment
You read three cells from the employee table using only their ids: one employee's name, another's department and a third's salary, and print each with its own label.
What you will do
- Build each id from the employee number and the column name the task gives, following the pattern above.
- Find each cell with
By.id()and read it withgetText(). - Print the three lines in the order and with the labels the task shows.
Common mistakes
Getting the id case wrong
The ids are case-sensitive:
emp3deptdoes not matchemp3Deptand throwsNoSuchElementException.Using a column name that is not in the id
The department column is
Deptin the ids, notDepartmentas in the header.Asking for a row that does not exist
emp6Namedoes not exist and throwsNoSuchElementException; check how many rows the table has first.
In a real test suite
Apps that generate ids from record keys, such as order-1042-status, make table checks simple and stable. When ids are missing, teams often ask developers to add data-testid attributes rather than rely on row positions.
Lesson 64 read the headers. Lesson 66 counts how many rows and columns the table has.
Related lessons
- Find Element by ID
By.id(), the locator used for each cell. - Iterate All Table DataRead every row when you need more than a few cells.
- XPath - BasicsXPath, for reaching a cell by row and column when there is no id.
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;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Tables");
// TODO: Get specific cell values by ID
// TODO: Print each value
driver.quit();
}
}