Abdulmalik Zoubi Abdulmalik Zoubi - 2 days ago 4
Java Question

Printing table to the console with selenium Java

I am trying to print the data of table from this site

http://www.lufthansa.com/online/portal/lh/il/homepage

try to make a book then you will see the availability
of the flights this is my code :

From this html code I want to print the branded-fares-flights table

String from_to = driver.findElement(By.cssSelector("table.branded-fares-flights")).getText();
System.out.println(from_to);


Its not working. It tells me that there is no such element.

Answer

As per your code, it seems you have identified only table element using cssSelector(driver.findElement) and then trying to print all its content, it won't work. You have go down the level from table to tr/td then print its text. Also since in your case multiple element will be returned so you to have use driver.findElements instead of driver.findElement. Try with the below code, you might need to modify little bit as per your requirement.

// Get all the table row elements from the table 
List<WebElement> allRows = driver.findElements(By.xpath("//table[@class='branded-fares-flights']//tr")); 

// And iterate over them and get all the cells 
for (WebElement row : allRows) { 
    List<WebElement> cells = row.findElements(By.tagName("td")); 

    // Print the contents of each cell
    for (WebElement cell : cells) {         

    System.out.println(cell.getText());
    //Or try below code 
    //System.out.println(cell.getAttribute("innerHTML"));
}
Comments