Zoran
Zoran

Reputation: 499

Iterate through table with li elements

Could someone please assist in following issue: I have a table of dynamic data(s) and every row has 5 elements in it (there are 30 rows). I have to iterate through each of rows, pickup data of every column and check if it is not a zero. Here is how it looks on page (actually it is picked up from xpath):

/html/body/main/article/div/div[3]/div[1]/div/div/ol[1]/li[3]/div[1]/a

Above is first user with its username. All usernames (from that table) I see:

/html/body/main/article/div/div[3]/div[1]/div/div/ol[1]/li/div[1]/a

As you can see last li has not a number, and when it has, it points to a username on position: 1, 2, 3 .... 30 So, my question is, how can I use inside that li element iteration. I tried this:

First found size of table:
int all = driver.findElements(By.xpath("/html/body/main/article/div/div[3]/div[1]/div/div/ol[1]/li/div[1]/a")).size();
    for (int i = 0; i < all; i++) {
    //check if username exists and convert int to a string
    String j = Integer.valueOf(i);

And finally put that into found xpath element (last li):

driver.findElements(By.xpath("/html/body/main/article/div/div[3]/div[1]/div/div/ol[1]/li["+get(j)+"]/div[1]/a"))

What am I doing wrong and not getting changed li[current number] in every iteration? Thank you in advance enter image description here

Here is HTML:

<li class="list-item row">
<div class="column large-4 compete-standings-user">
 <div class="user-photo"><img 
 <a "profile/kalaka" title="Kalaka">Kalaka</a>
 <div class="column large-2 small-3 compete-standings-data">
 <strong>71</strong>blogs</div>
 <div class="column large-2 small-3 compete-standings-data">
 <strong>+69.9</strong>Accepted</div>
 <div class="column large-2 small-3 compete-standings-data">
 <strong>+21.1%</strong>Pending</div>
 <div class="column large-2 small-3 compete-standings-datae">
 <strong>L100</strong>Earned</div>

enter image description here

Upvotes: 0

Views: 841

Answers (1)

JeffC
JeffC

Reputation: 25724

So the quick way to get the text that you want to check is to use the CSS selector, ol.compete-standings > strong. If you notice the HTML, each of the numbers that you want to check are in a STRONG tag. This locator gets all the STRONG tags inside the outer OL tag.

List<WebElement> numbers = driver.findElements(By.cssSelector("ol.compete-standings > strong"));
for (WebElement number : numbers)
{
    String s = number.getText().replaceAll("[^\\d]", "");
    Assert.assertNotEquals(0, Integer.parseInt(s));
}

This code strips out all characters except for numbers, converts the string to an int, and asserts (using TestNG) that the number is not zero. If you aren't using TestNG (or the equivalent)... you should be :). You can just sub in your own validation.

Upvotes: 1

Related Questions