Handle Dynamic Html Tables Use Selenium WebDriver

Html table is widely used in web page. This article will show you examples about how to access html table use selenium webdriver in your automation test script.

Generally web designer will not give id or name value to a table. So we had better use xpath to access them.

There are two tables in below example, a big table which contain a small table.

Example 1 : Read the text “Selenium” in red cell using xpath.

Because the text “selenium” is located in outer table line two and cell one. So we can use below xpath to locate it. //table/tbody/tr[2]/td[1]. Please note // means find after html tag in every dom tree level. / means find after html tag in current dom tree level.So //table/tbody/tr[2]/td[1] will find /tbody/tr[2]/td[1] under both the outer and inner tables. You can read article Selenium XPath Css Selector Example for more xpath examples.

Because the cell that contain the text “selenium” has unique attribute style="background-color:red;color:yellow", so we can also locate it with//td[@style="background-color:red;color:yellow"]

Because the text “selenium” is unique, so we can also use //td[contains(text(),"selenium")]

Use //table[@style="width:100%"]/tbody/tr to get all row web element list in outer table. Please note we use outer table’s style attribute to identify it.

Loop in the row web element list, for each row, use xpath ./td to get current row’s cell web element list. Please note the dot in xpath, one dot means find td in current web element( current tr ), two dot means find in parent web element.

Text “testing” is located in inner table row one column two, so we can use below xpath //table//table/tbody/tr[1]/td[2] to get it. Please note even the source html code do not have tbody html tag for the nested inner table, but some web browser like Chrome, Firefox will add it automatically. So we had better use Chrome inspector or Firefox firebug to get the xpath exactly, then modify it as we need. You can read article How To Find Web Element Using Web Browser Inspector.

Nested inner table has unique attribute width=80%, so we can use //table[@width="80%"]//td[2].

The target cell contains unique text “testing”, so we can use//td[contains(text(),"testing")] also.

The target cell has unique attribute style="background-color:green;color:yellow", so below xpath is also effective. //td[@style="background-color:green;color:yellow"].