-2

I am trying to print a Webtable-specific column that is Salary and am notable to figure out how to do that please help.


import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Table {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();

driver.get("https://datatables.net/examples/basic_init/test.html"); 
WebElement table =driver.findElement((By.xpath("//*[@id=\"example\"]/tbody/tr[1]/td[6]")));
Thread.sleep(10000);
for (WebElement td: table){
    System.out.println(td.getText());
}  

    driver.quit();  
} 

  }
}

2 Answers2

0

I'm not sure what is the problem here.

This block of code works for me on raw Selenium

WebDriver driver = new ChromeDriver();
driver.get("https://datatables.net/examples/basic_init/test.html");

 driver.findElements(new By.ByCssSelector("[id=example] tr[class]")).forEach(row ->
    {
        String result = row.findElements(new By.ByTagName("td")).get(5).getText();
        System.out.println(result);
    });

where expectedRow - is the index of row with Salary and 5 - index of Salary column.

For sure this can be wrapped in separate method and there can be automatic column index search by getting index of th which contains aria-label "Salary", but you can do it by our own if you need it :)

Yaroslavm
  • 1,762
  • 2
  • 7
  • 15
0

The Salary is within the 6th descendant i.e. the last <td> of it's parent <tr>


Solution

To print the text from the Salary column 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:

    driver.get("https://datatables.net/examples/basic_init/test.html");
    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("table#example tbody tr td:nth-child(6)"))).stream().map(element -> element.getText()).collect(Collectors.toList()));
    
  • Using xpath:

    driver.get("https://datatables.net/examples/basic_init/test.html");
    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//table[@id='example']//tbody//tr//td[last()]"))).stream().map(element -> element.getText()).collect(Collectors.toList()));
    
  • Console output:

    [$162,700, $1,200,000, $86,000, $132,000, $206,850, $372,000, $163,500, $106,450, $145,600, $433,060]
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352