Home > Blockchain >  Selenium: How to get all the h3 text with getText()
Selenium: How to get all the h3 text with getText()

Time:08-14

In the webpage https://cloudwise.nl/dit-is-cloudwise/alle-cloudwisers/directie/ I'm trying to get all users' names using for loop.

What I have tried so far is:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(@class,'inner')]/h3"))).getText();

and

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(@class,'inner')]/h3"))).getAttribute("innerHTML");

But all of them gets text Directie instead of users' name. I think it's because of the users' name is in a header <h3> tag and it just ignores it. How can I get the users' name within a header tag?

CodePudding user response:

You were close enough. visibilityOfElementLocated() will always return you the first matching element, where as you need all the matching elements.


Solution

To print the list of users you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use Java8 stream() and map() and you can use either of the following Locator Strategies:

  • Using cssSelector:

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.inner h3"))).stream().map(element->element.getText()).collect(Collectors.toList()));
    
  • Using xpath:

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[contains(@class,'inner')]//h3"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
    
  • Related