0

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

// 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
}
4

2 回答 2

2

好的。您的问题是 tdList 是List<WebElement>,并且WebElement不能转换为字符串。

如果您使用的是编译器,您可能会在 Iterator 行上收到警告,说它是通用的。你需要有那条线Iterator<WebElement> iter = tdlist.iterator();。然后你可以做itr.next().getText(),你不必施放任何东西!

于 2013-08-14T18:17:56.847 回答
0

这是我的猜测:

// Create a List composed of objects from the Client_Totals table
List<WebElement> tdlist = driver.findElements(By.cssSelector("selector text"));
for ( WebElement el: tdlist ) {
    System.out.println( el.getText() );
    Assert.assertTrue( el.getText().equalsIgnoreCase("a message"), 
        "There was no message."); 
    Assert.assertTrue( el.getText().equalsIgnoreCase("11 - 25 User Discount"), 
        "There was no 11 - 25 User Discount.");
    Assert.assertTrue( el.getText().equalsIgnoreCase("$17.55"), 
        "There was no $17.55.");
    Assert.assertTrue( el.getText().equalsIgnoreCase("$4829.40"), 
        "There was no $4829.40.");
}
于 2013-08-14T22:04:04.723 回答