gpt4 book ai didi

Java:Selenium:WebDriver:无法解析 List 对象;获取错误 "cannot be cast to java.lang.String"

转载 作者:行者123 更新时间:2023-12-02 06:49:19 24 4
gpt4 key购买 nike

我是java编程新手,我有一个关于解析List<WebElement>的问题目的。我有一个 selenium webdriver 脚本(用 java 编写),可以解析 List<WebElement>目的。工作代码的代码片段如下。

// Create a List composed of objects from the Client_Totals table
List<WebElement> tdlist = driver.findElements(By.cssSelector("table[class='client_totals'] tr td")); // 8-12-13 -- This Code Works -- KV

for(WebElement el: tdlist)
{
System.out.println(el.getText());
}

这段代码可以工作,但我需要修改脚本,以便脚本:

  1. 检查以下值:
    • (a) 11 - 25 位用户折扣
    • (b) 17.55 美元 (c) 4829.40 美元
  2. 输出消息,通知用户是否成功找到值。

我开始使用迭代器循环遍历 tdlist 来编写一个新的修改脚本(见下文),但出现以下错误:java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.lang.String

// Create a List composed of objects from the Client_Totals table
List<WebElement> tdlist = driver.findElements(By.cssSelector("table[class='client_totals'] tr td"));
Iterator itr = tdlist.iterator();
while(itr.hasNext())
{
String value= (String)itr.next();
System.out.println("Value : "+value);
}

我的评估:我认为发生错误是因为 tdlist 属于不同类型,并且为了工作,tdlist 需要“转换”为字符串数组。但是,我不知道该怎么做。

接下来,我还需要在 while 结构中添加嵌套的 IF ELSE 语句。我已经根据我认为适当的代码结构编写了伪代码:

While there are elements in the array
{
Parse through the array
If value "11 - 25 User Discount" is found
Print message "11 - 25 User Discount was found"
Else If value "$17.55" is found
Print message "$17.55 was found"
Else If value "$4829.40" is found
Print message "$4829.40 was found"
Else
End While Loop
}

最佳答案

好的。你的问题是 tdList 是 List<WebElement> ,和WebElement无法转换为字符串。

如果您使用编译器,您可能会在迭代器行上收到警告,指出它是通用的。您需要将该行设置为 Iterator<WebElement> iter = tdlist.iterator(); 。那么你可以做itr.next().getText()而且您无需转换任何内容!

关于Java:Selenium:WebDriver:无法解析 List<WebElement> 对象;获取错误 "cannot be cast to java.lang.String",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18239152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com