【问题标题】:java.lang.ClassCastException: class org.openqa.selenium.By$ByXPath cannot be cast to class org.openqa.selenium.WebElementjava.lang.ClassCastException:类 org.openqa.selenium.By$ByXPath 不能转换为类 org.openqa.selenium.WebElement
【发布时间】:2020-03-25 06:20:43
【问题描述】:
我正在尝试使用 Page 对象模型自动化 selenium web 驱动程序中的单选按钮。
下面是我的代码解释:
By AutomaticDataLockTimed = By.xpath("//span[@class='ant-radio']//input[@name='automaticDataLock']");
if (!((WebElement) AutomaticDataLockTimed).isSelected()) {
JSUtil.clickElementUsingBySelector(AutomaticDataLockTimed, driver);
}
}
我收到以下错误消息
java.lang.ClassCastException: 类 org.openqa.selenium.By$ByXPath 不能
转换为 org.openqa.selenium.WebElement 类(org.openqa.selenium.By$ByXPath 和 org.openqa.selenium.WebElement 位于加载程序“app”的未命名模块中)
我已经参考了这个链接java.lang.ClassCastException: org.openqa.selenium.By$ById cannot be cast to org.openqa.selenium.WebElement
但是这个链接没有回答我的情况。
我认为这是由于我的 if 语句中的转换问题,但我无法修复。
请帮忙!
【问题讨论】:
标签:
java
selenium
selenium-webdriver
casting
selenium-chromedriver
【解决方案1】:
您正试图在 AutomaticDataLockTimed 上调用 .isSelected(),这是一个 By 对象,但 isSelected() 是 WebElement 上的一个方法——这就是您的异常的来源。
我看到您正在尝试将 By 转换为 WebElement,但这不是解决问题的正确方法。在调用isSelected() 之前,您需要使用WebDriver 实例来定位具有AutomaticDataLockTimed 的元素:
编辑:此答案已更新为使用getAttribute("value") 而不是用户指定的isSelected()。我将按原样保留答案描述以匹配原始问题描述。
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);
}
请记住,您应该在脚本的开头以 WebDriver 开头:
WebDriver webdriver = new ChromeDriver();
希望这会有所帮助。
【解决方案2】:
这对我有用。
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();
}