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

拜拜、爱过 提交于 2021-02-05 08:10:19

问题


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?


回答1:


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:

  • findElement()
  • findElements

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.



来源:https://stackoverflow.com/questions/51972824/java-lang-classcastexception-java-base-java-lang-string-cannot-be-cast-to-org-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!