1

I am trying to iterate through a list of columns for a table header row, and need to print out the text of the element (getText()). How can this be done when there are many columns (td) for the specific table header row? Below is the XPATH and a screenshot showing the columns (count of 54 columns):

XPATH expresssion for table header row: //*[@id="accuracyTableWrapper"]/table/thead/tr

XPATH expresssion for table column: //*[@id="accuracyTableWrapper"]/table/thead/tr/td (where there are 54 instances of this)

Screenshot: enter image description here

How can this be done efficiently in order to properly print out the text for each td? Please let me know for any suggestions.

Shawn
  • 4,064
  • 2
  • 11
  • 23
wheelerlc64
  • 435
  • 2
  • 5
  • 17

2 Answers2

1

Given the HTML...

html

the elements seems to be dynamic elements, so to print the desired texts ideally you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use the following locator strategies:

  • Using cssSelector:

    List<WebElement> elements = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#accuracyTableWrapper > table > thead > tr td")));
    for(WebElement element : elements)
    {
      System.out.println(element.getText());
    }
    
  • Using xpath:

    List<WebElement> elements = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@id="accuracyTableWrapper"]/table/thead/tr//td")));
    for(WebElement element : elements)
    {
      System.out.println(element.getText());
    }
    

Using Java8's stream() and map() you can use the following locator strategies:

  • Using cssSelector:

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#accuracyTableWrapper > table > thead > tr td"))).stream().map(element->element.getText()).collect(Collectors.toList()));
    
  • Using xpath:

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@id="accuracyTableWrapper"]/table/thead/tr//td"))).stream().map(element->element.getText()).collect(Collectors.toList()));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

Below code will print all the text within the td nodes:

List<WebElement> tdList = driver.findElements(By.xpath("//*[@id=\"accuracyTableWrapper\"]/table/thead/tr/td"));
        for (WebElement element : tdList) {
            System.out.println(element.getText());
}
Shawn
  • 4,064
  • 2
  • 11
  • 23