Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver - Fetching Table Data

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
 }
}
like image 837
Sky Avatar asked May 17 '12 05:05

Sky


People also ask

How get all data from a table in Selenium?

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 Webtable in Selenium?

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.


1 Answers

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("./*"));
like image 155
JacekM Avatar answered Sep 23 '22 22:09

JacekM