Working with tables using Selenium WebDriver

December 29, 2016

In any Web Application representing data and fetching the data from tables is a usual scenario. In this tutorial (working with tables using selenium webdriver) we will learn How to work with static or dynamic table and fetch data?

Fetching Data from Static Tables

Tables in HTML are represented with <table> tag. Rows in a table are represented with <tr> tag and cells/data in a row is represented with <td> tag.

Generally, developers do not provide id’s to rows (<tr> tags) and cells (<td> tags). In that case, we are left with one option to write dynamic XPath.

Let us consider a table which has two columns – Subject Name and Subject code

working_with_tables_using_selenium_webdriver

If we see the html code of the above table, there is an Id (id=’subject_code_table’) assign to this table; we can use this Id in Xpath locator to identify the table. Now to go inside this table, we will be accessing the rows and columns.

Let say the scenario was to fetch subject code of Maths. In this case, we can write its xpath as below:

Xpath:

Fetching Data from Dynamic Tables

Now sometimes these tables get data dynamically, say it is updated from some database. To iterate a table and fetch code of each subject, we can first fetch the number of rows from the table and then iterating over each row we can fetch the number of cells from each row and then iterate over each cell till we get the required field.

The above code you see fetches the number of rows from a table and then iterating over each row to get the number of cells from a row. In next step, a loop is written to get the number of cells from each row and iterating over each cell to fetch the text written in it. As in above table number of cells in each row is 2. The first value will return Subject name and second value will return its value. If the cell value is equal to a particular subject (say Maths), from the second cell we are fetching the subject code.

Comment below if you have any questions regarding how to working with tables using selenium webdriver!

PS: For any questions, queries and feedback, feel free to write us at saurabh@qatechhub.com or support@qatechhub.com. Happy Learning 🙂

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: