类型转换Webelement to Select时出错

时间:2015-02-09 10:21:19

标签: java selenium selenium-webdriver

  1. 在我的网页中,有多个dropdowns具有相同的属性值

  2. 我在列表

  3. 中获取了所有Webelements
  4. 现在使用索引

  5. 从列表中提取一个WebElement
  6. 在尝试输入此WebElement时,选择我收到错误:

  7.   

    " java.lang.ClassCastException:   org.openqa.selenium.remote.RemoteWebElement无法强制转换为   org.openqa.selenium.support.ui.Select"

    请帮忙!以下是我的代码。

    int index;
    String sIndex = null;
    By element = ORUtils.ORGenerator(pageName,objectName);
    //Getting all the webelements with same name in myElement List
    java.util.List<WebElement> myElements=WebUtils.driver.findElements(element);
    
    //Get index of element on page
    Pattern pIndex=Pattern.compile("(.*)");
    Matcher mIndex=pIndex.matcher(objectName);
    if(mIndex.find())
    {
        sIndex=objectName.replaceAll("[a-z]","");
        sIndex=sIndex.replaceAll("[A-Z]","");
    }
    
    index=Integer.valueOf(sIndex);
    index=index-1;
    //Getting element from the List using index
    WebElement myElement=myElements.get(index);
    
    //Type casting WebElement to Select this is where i get the error**
    Select myDropDown=(Select) myElement;
    
    List<WebElement> listOfOptions = myDropDown.getOptions();
    //List<WebElement> listOfOptions=myElement.
    for(WebElement item : listOfOptions)
    {
        if(Value.equals((item.getText())))
        {
            item.click();
            Thread.sleep(2000);
            break;
        }
    }
    

1 个答案:

答案 0 :(得分:4)

在java对象类型转换中,可以将一个对象引用类型转换为另一个对象引用。强制转换可以是自己的类类型,也可以是其子类或超类类型或接口之一。所以你所做的是不正确的。要使用myElement创建Select对象,请执行以下操作:

Select myDropDown=new Select(myElement);

要了解更多信息,您还可以通过查看instanceOf来试用。在这里,您可以将其检查为:

if (myElement instanceof Select)
    System.out.println(true);
else
    System.out.println(false);

你会得到答案。