Reputation: 97
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
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
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 div
s located in the 5th column of each row.
Upvotes: 1