Reputation: 5396
I have one simple table and I want to get count of each TR and it's TDs , But my code is returning me total TD count of page.
List<WebElement> TRcount = driver.findElements(By.tagName("tr"));
System.out.println(TRcount.size());
if(TRcount.size()>0)
{
for(int i=0;i<TRcount.size();i++)
{
List<WebElement> TDcount = driver.findElements(By.tagName("td"));
System.out.println("First TR Contains: " + TDcount.size());
}
}
Table Code :
<table class="tftable" border="1">
<tr><th>PREVIOUS TEST</th><th>CURRENT TEST</th></tr>
<tr><td>Row:1 Cell:1</td><td>Row:1 Cell:2</td></tr>
<tr><td>Row:2 Cell:1</td><td>Row:2 Cell:2</td></tr>
</table>
I want code which return me like 1st TR contains 2 TD , 2nd TR contains 2 TD.
My current code returns me total 4 TD. But I want TR wise TD count.
Upvotes: 0
Views: 4272
Reputation: 12623
You can perform a findElements()
on the individual WebElement of the <tr>
tags.
List<WebElement> TRcount = driver.findElements(By.tagName("tr"));
for(WebElement e : TRcount) {
List<WebElement> TDcount = e.findElements(By.tagName("td"));
System.out.println("First TR Contains: " + TDcount.size());
}
OR
for(int i=0; i<TRcount.size(); i++) {
List<WebElement> TDcount = TRCount.get(i).findElements(By.tagName("td"));
System.out.println("First TR Contains: " + TDcount.size());
}
EDIT:
For fetching text from the individual <td>
tags.
for(int i=0; i<TRcount.size(); i++) {
List<WebElement> TDcount = TRCount.get(i).findElements(By.tagName("td"));
System.out.println("First TR Contains: " + TDcount.size());
// Fetch text from individual '<td>' tags
for(int j=0; j<TDcount.size(); j++) {
System.out.println(TDcount.get(j).getText());
}
}
Upvotes: 1