Home > OS >  Printing specific column value from a webTable
Printing specific column value from a webTable

Time:04-29

I am trying to print all the column values from a table based on a parameter. If the paramter matches then all the column values should be printed. This is not happening in my code below.


public class DynamicTableHandling extends DriverFactory {

  static String company = "ABB India Ltd.";

  public static void main(String[] args) {

    init_driver("chrome");
    driver.get("https://money.rediff.com/sectors/bse/power");
    extractTableValues(company);
}

public static void extractTableValues(String company) {
  //print all the column values from the table when the company name provided has matched//
    
 List<WebElement> tableRow = driver.findElements(By.xpath("//table[@class='dataTable']/tbody/tr"));

    for (int row = 0; row < tableRow.size(); row  ) {

        WebElement colData = tableRow.get(row);

        List<WebElement> tableCol = colData.findElements(By.tagName("td"));

        for (int col = 0; col < tableCol.size(); col  ) {
            String result = tableCol.get(col).getText();

            if (company.equals(result.trim())) {
                System.out.print(result   " | ");
                break;
            }
        }
    }

}

}

Output -- ABB India Ltd. |

CodePudding user response:

The current method that you've extractTableValues has a complexity of O(n^2). You can significantly optimize to have a O(n) by making a dynamic xpath.

Your effective code:

public static void extractTableValues(String company) {
    List<WebElement> tds = driver.findElements(By.xpath("//a[contains(.,'" company "')]//ancestor::tr//td"));
    for (WebElement td : tds) {
        System.out.println(td.getAttribute("innerText"));
    }
}

Output:

ABB India Ltd.
A
2090.10
2084.35
 5.75
 0.28

Or Using Java 1.8:

public static void extractTableValues(String company) {
    List<WebElement> tds = driver.findElements(By.xpath("//a[contains(.,'" company "')]//ancestor::tr//td"));
    tds.stream().forEach(td -> {System.out.println(td.getText());});
}
  • Related