简体   繁体   中英

java.lang.ClassCastException: class org.openqa.selenium.By$ByXPath cannot be cast to class org.openqa.selenium.WebElement

I am trying to automate radio button in selenium web driver using Page object model. Below is my code explanation:

By AutomaticDataLockTimed = By.xpath("//span[@class='ant-radio']//input[@name='automaticDataLock']");

if (!((WebElement) AutomaticDataLockTimed).isSelected()) {
            JSUtil.clickElementUsingBySelector(AutomaticDataLockTimed, driver);
        }
    }

and I am getting below error message

java.lang.ClassCastException: class org.openqa.selenium.By$ByXPath cannot be cast to class org.openqa.selenium.WebElement (org.openqa.selenium.By$ByXPath and org.openqa.selenium.WebElement are in unnamed module of loader 'app')

I have referred this link java.lang.ClassCastException: org.openqa.selenium.By$ById cannot be cast to org.openqa.selenium.WebElement

but this link did not answer my scenario.

I think it is due to casting problem in my if statement but I cannot fix.

Please help!

You are trying to call .isSelected() on AutomaticDataLockTimed , which is a By object, but isSelected() is a method on a WebElement -- that's where your exception is coming from.

I see that you are trying to cast By to WebElement , but that's not the right way to solve the issue. You need to use your WebDriver instance to locate an element with AutomaticDataLockTimed before you can call isSelected() :

EDIT : This answer has been updated to use getAttribute("value") instead of isSelected() , as specified by the user. I am leaving answer description as-is to match original problem description.

By AutomaticDataLockTimed = By.xpath("//span[@class='ant-radio']//input[@name='automaticDataLock']");

// locate the element using AutomaticDataLockTimed locator
WebElement element = webdriver.findElement(AutomaticDataLockTimed);

if (!element.getAttribute("value").equals("true"))
{
    JSUtil.clickElementUsingBySelector(AutomaticDataLockTimed, driver);
}

Remember, you should have started WebDriver at the beginning of your script as such:

WebDriver webdriver = new ChromeDriver();

Hope this helps a bit.

This worked for me.

   List<WebElement> list = driver.findElements(WEBELEMENT);
    for (int i = 0; i < list.size(); i++) {
        String str = list.get(i).getAttribute("value");
        if (str.equals("true")) {
            list.get(i).click();
        }

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