0

I want to count elements in selenium. When using xpath //*[@class='z-listbox-body']/table/tbody[2]/tr I get 3 matching nodes.

But my code gets 12 instead of 3:

public String countTable(){
    List<WebElement> located_elements = driver.findElements(By.xpath("//*[@class='z-listbox-body']/table/tbody[2]/tr"));
    int count = 0;
    for(WebElement located_element:located_elements){
        count ++;
    }
    String s = String.valueOf(count);

    return s;
}
Kim Hogeling
  • 641
  • 6
  • 14
Mai Thanh
  • 9
  • 1
  • 1
    Does `located_elements.size()` also return 12, or 3? – Kim Hogeling Mar 20 '18 at 01:51
  • So which one is correct _using xpath `//*[@class='z-listbox-body']/table/tbody[2]/tr` or your code_? – undetected Selenium Mar 20 '18 at 05:33
  • What is the number of matching elements when you search with your XPath expression in ChromeDevelopers Tools? How to check that see: :https://stackoverflow.com/questions/22571267/how-to-verify-an-xpath-expression-in-chrome-developers-tool-or-firefoxs-firebug – Frank Mar 20 '18 at 07:53
  • Frank, I get 3 matching nodes , but my code gets 12 .:( – Mai Thanh Mar 20 '18 at 09:20
  • When you are debugging the code and have a look on the content of the list, what is inside this list? How are this webelements looks like? – Frank Mar 21 '18 at 07:48

1 Answers1

0

Please try to use below code:

public String countTable(WebDriver dirver){ 
    List located_elements = driver.findElements(By.xpath("//[@class='z-listbox-body']/table/tbody[2]/tr")); 
    return String.valuseOf(located_elements.size());

}

Alex Bruce
  • 533
  • 2
  • 10
  • 23
  • 1
    What have you changed - removed the typing on List and use .size() instead of manually counting the contents of the list? Can you explain why the for loop would give the wrong answer? – Rup Mar 20 '18 at 02:06
  • when i search in web result 3 matching nodes. i try List located_elements = driver.findElements(By.xpath("//[@class='z-listbox-body']/table/tbody[2]/tr")); return String.valuseOf(located_elements.size()); but my code gets 12 instead of 3: – Mai Thanh Mar 20 '18 at 03:44