Search code examples
seleniumselenium-webdriverclasscastexception

java.lang.ClassCastException while Fetching number of rows and columns from Dynamic Webtable


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.WebElement;

    public class WebTable {


    public static void main(String args[])throws ParseException{
    WebDriver wd;
    System.setProperty("webdriver.chrome.driver","E:\\Selenium-2017\\chromedriver_win32\\chromedriver.exe");

    wd = new ChromeDriver();
    wd.get("http://money.rediff.com/gainers/bsc/daily/groupa");

    List<WebElement> col = (List<WebElement>) wd.findElement(By.xpath(".//*[@id='leftcontainer']/table/thead/tr/th"));
    System.out.println("No of cols are : " +col.size());
     List<WebElement> rows = (List<WebElement>) wd.findElement(By.xpath(".//*[@id='leftcontainer']/table/tbody/tr[1]/td[1]"));
     System.out.println("No of rows are :" +rows.size());
     wd.close();
    }
    }

Getting Below exception :

Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 44959
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.List
    at WebTable.main(WebTable.java:17)

Solution

  • findElement returns a WebElement, which cannot be cast to a List of WebElements. Remove the cast (List<WebElement>) and use findElements() (with an 's') instead.

    See this SO question and this tutorial