Search code examples
javaseleniumcss-selectorsui-automationselenide

Taking element with css selector with multiple elements in a table


I am using Selenide/Selenium to write my java automation scripts and recently I faced a problem. I want to take an element from the same row I compare my second element. Html example code:

<tr ng-repeat="testing" class="ng-scope" style="">
    <td class="ng-binding">Style</td>
    <td ng-if="testing2" class="ng-binding ng-scope">1</td>
    <td class="ng-binding">5%</td>
</tr>
<tr ng-repeat="testing" class="ng-scope" style="">
    <td class="ng-binding">Mask</td>
    <td ng-if="testing2" class="ng-binding ng-scope">2</td>
    <td class="ng-binding">8%</td>
</tr>
...

Let's imagine there will be much more of those. And the most important one is that these can be randomised. every single time. They depend on last page what I select and how.

So basically I want to search for testing and that it has 8%.

What I tried but I don't know what to do with it. It stores all elements in list. Bu I get css selector with Chrome driver info before it. I can take it off but I think there is much better solutions:

List<WebElement> list = getWebDriver().findElements(By.cssSelector("[ng-
repeat='hyvitisLiik in vm.taotluseHyvitised'] > [class='ng-binding']"));
for(int i = 0; i < list.size(); i++){
  logger.info(list.get(1));
}

I also tried to get an element with this code:

int counter = $$(By.cssSelector("tr > [class='ng-binding']")).size();
for (int i = 0; i < counter; i++) {
SelenideElement word= $$(By.cssSelector(lokaator)).get(counter);
word.getText();
}

This code takes the "Mask" and a "8%" elements. But what I really want is test if the getText given value is "Mask", take the percent value and compare it. For example: search in web for the word "Mask", take the percent value (in that case it is 8%) and validate with assert that it is exactly 8%.

Is there any way to set CSS selector with index, like

tr[1] > [class='ng-binding']

which will select for the second tr class? any other advice to find I want?

EDIT: Is it possible to get the element with css selector using only one row as showed with xpath option in answer what wrote @Guy:

WebElementelement=getWebDriver().findElement(By.xpath("//td[text()='Mask']/followingsibling::td[2]"));
element.getText(); // 8%

Solution

  • You can use xpath to locate the element using the Mask text

    WebElement element = getWebDriver().findElement(By.xpath("//td[text()='Mask']/following-sibling::td[2]"));
    element.getText(); // 8%