![](/img/trans.png)
[英]java.lang.ClassCastException: org.openqa.selenium.By$ById cannot be cast to org.openqa.selenium.WebElement
[英]java.lang.ClassCastException: class org.openqa.selenium.By$ByXPath cannot be cast to class org.openqa.selenium.WebElement
我正在嘗試使用 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 在未命名的模塊中加載器“應用程序”)
但此鏈接沒有回答我的情況。
我認為這是由於我的 if 語句中的轉換問題,但我無法修復。
請幫忙!
您正在嘗試在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();
希望這個對你有幫助。
這對我有用。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.