简体   繁体   中英

java.lang.ClassCastException: java.base/java.lang.String cannot be cast to org.openqa.selenium.WebElement when executing test through Selenium

I'm trying make an automation test in Selenium WebDriver, but Eclipse is showing me the following error:

java.lang.ClassCastException: java.base/java.lang.String cannot be cast to org.openqa.selenium.WebElement

Here is my code:

public void SeachApp()
{
    Object elem = driver.getPageSource().contains("Staffing");

    if (elem != null)
    {
        System.out.println("Encontrado");
        int width = ((WebElement) elem).getSize().getWidth();

        Actions act = new Actions(driver);
        act.moveToElement((WebElement) elem)
            .moveByOffset((width / 2) - 15, 0)
            .click()
            .perform();
        }
        else
        {
            System.out.println("Não Encontrado");
        }
    }

What's going on, and how can I fix this?

getPageSource()

As per the documentation getPageSource() returns the source of the current page and is defined as:

Get the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page. You need to follow the documentation of the particular driver being used to determine whether the returned text reflects the current state of the page or the text last sent by the web server. The page source returned is a representation of the underlying DOM: do not expect it to be formatted or escaped in the same way as the response sent from the web server.


contains()

The contains() method is a Java method to check if the String contains another substring or not. It returns boolean value so it can use directly inside if statements.


Analysis

The expression which you have used:

driver.getPageSource().contains("Staffing");

will return a Boolean Value but gets casted into an Object type of object. Further, as you are trying to cast an Object type of object to WebElement type you see the error as:

java.lang.ClassCastException: java.base/java.lang.String cannot be cast to org.openqa.selenium.WebElement

Solution

If you desire to locate a WebElement you have to use either of the following methods:

Now, if you desire to get hold of the WebElement with text as Staffing (without any reference to the relevant HTML ) you can use the following solution:

WebElement element = driver.findElement(By.xpath("//*[contains(text(),'Staffing')]"));

Now, once you located the WebElement , you can easily perform the remaining of your tasks with the WebElement .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM