Search code examples
javalistwebdrivertestngparents

how to use List<WebElement> webdriver


I am creating an automatic test for some webs and I'm using WebDriver, TestNG and code that is written in Java. On the page is shown register of categories, in parentheses is number of auctions and i need to get this number as variable.

I use this code

By bycss =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse = driver.findElement(bycss );
String text_vse1_1 = number1_1_vse.getText();

but I get only first number and i need to get all. Someone advised me that I should use List. But when i use it, i get only

[[[[[[[FirefoxDriver: firefox on WINDOWS (7e6e0d0f-5cbb-4e48-992f-26d743a321a5)] -> css selector: .list.list-categories>li:first-child]] -> xpath: ..]] -> xpath: .//*], [[[[[[FirefoxDriver: firefox on WINDOWS (7e6e0d0f-5cbb-4e48-992f-.....

code:

By bycss2 =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse2 = driver.findElement(bycss2 );
WebElement parent1 = number1_1_vse2.findElement(By.xpath(".."));
List<WebElement> childs1 = parent1.findElements(By.xpath(".//*"));
System.out.println(childs1);

link to the website

screenshot -> image with the number

can anyone advise me please?


Solution

  • Try the following code:

    //...
    By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
    List<WebElement> myElements = driver.findElements(mySelector);
    for(WebElement e : myElements) {
      System.out.println(e.getText());
    }
    

    It will returns with the whole content of the <li> tags, like:

    <a class="extra">Vše</a> (950)</li>
    

    But you can easily get the number now from it, for example by using split() and/or substring().