user3713453
user3713453

Reputation: 97

Selenium WebDriver - how to get elements of tables and iterate through rows

I want to iterate tables per row, In my test scenario i will look for a certain data for each rows. I already done this by using Absolute Xpath. Is there another better/alternative way other than using Absolute Xpath for iterating through these rows?

This is the logic of my code before:

private static int iRow;

WebElement sWorkUnitRows = null;

for (iRow = 1; iRow <= 10; iRow++) {

sWorkUnitQuery = driver.findElement(By.Xpath("html/body/div[2]/div[4]/div/div/div[3]/div[1]/table/tbody/tr["+ iRow + "]/td[5]/div"));

// Do some actions here, click and verify data for each rows until it finds the specific data

break;

}

Any ideas for this? Will highly appreciate any inputs thanks!

Upvotes: 0

Views: 4190

Answers (2)

robert arles
robert arles

Reputation: 183

First: If you can get IDs put on elements you are interested in, that is the best and fastest option. Most importantly, interface changes can be made without breaking your tests as long as the ID's are maintained.

To your question: I would recommend driver.findElements(), but would generally recommend not using XPath any time there is another option.

In this case, I'd use By.CssSelector to find the elements. Something like:

"tbody.listTbody tr"

Then extract the data from each item in the list of web elements that are returned. I'm guessing that if you are looking for data that you may not need to get all the way down to the div. Just get the text for the row, then if you find a match for your data, work with the div. You avoid checking for the div in the first place.

Upvotes: 1

Titus
Titus

Reputation: 22474

You can use findElements(...) instead of findElement(...).

Here is an example:

List<WebElement> elements = driver.findElements(By.Xpath(".//*/tr/td[5]/div"));
for(WebElement element:elements){
     ...
}

This will return a list of all the divs located in the 5th column of each row.

Upvotes: 1

Related Questions