I want to fetch data from tables in UI. I know about looping through rows and columns using "tr" and "td". But the one the table I have is something like this:
<table>
<tbody>
<tr><td>data</td><th>data</th><td>data</td><td>data</td></tr>
<tr><td>data</td><th>data</th><td>data</td><td>data</td></tr>
<tr><td>data</td><th>data</th><td>data</td><td>data</td></tr>
</tbody>
</table>
How can I make my code generic, so that the occurrence of "TH" in middle can be handled. Currently, I am using this code :
// Grab the table
WebElement table = driver.findElement(By.id(searchResultsGrid));
// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells) {
// And so on
}
}
We can get all the values inside a table in Selenium with the help of find_elements method. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned.
What is a Web Table in Selenium? A Web Table in Selenium is a WebElement used for the tabular representation of data or information. The data or information displayed can be either static or dynamic. Web table and its elements can be accessed using WebElement functions and locators in Selenium.
You could look for all children of tr element without differentiating between td and th. So instead of
List<WebElement> cells = row.findElements(By.tagName("td"));
I would use
List<WebElement> cells = row.findElements(By.xpath("./*"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With