How to get all direct(immediate) rows from WebElement Table

958 views Asked by At

From the below table I need immediate row elements using Xpath or "css-selector" or Selenium API :- element.findelements. Please help.

<table id ="Main">
<tbody>
<tr id="row_1">
<tr id="row_1_1">
<tr id="row_1_1_1">
</tr>
</tr>
</tr>
<tr id="row_2">
</tr>
<tr id="row_3">
<tr id="row_3_1">
</tr>
</tr>
</tbody>
</table>

Expected Output:-

[<tr id="row_1">,<tr id="row_2">,<tr id="row_3">]

Imp Note:- I am looking for a generic solution. Sometimes tbody wont be present in the table. I am having Table WebElement with me.

2

There are 2 answers

0
har07 On BEST ANSWER

You can use xpath union operator (|) to combine multiple xpath expressions, f.e one to handle the case when tbody exists, and another for the case when tbody doesn't exist :

//table[@id='Main']/tbody/tr | //table[@id='Main']/tr
4
Santoshsarma On

Use below locator

By.cssSelector("table#Main > tbody > tr")

Or

By.xpath("//table[@id='Main']/tbody/tr")


List<WebElement> allRows = driver.findElements(By.cssSelector("table#Main > tbody > tr"));
for(WebElement ele : allRows) {
    //do your operation with that row
    //ele.getText();
}