Selenium Webdriver java无法选择下拉选项

时间:2015-01-11 12:44:26

标签: java selenium

我已阅读并尝试了许多类似问题的回复,但我仍然无法从下拉控件中选择一个选项。我的代码:

//select a particular item in the returned list of companies from the company dropdown

Select oDropdown = new Select(driver.findElement(By.name("ctl00$wnCore$ctrlBrokerSelect$ddlSelectCompany")));

oDropdown.selectByVisibleText("broker1");

这总是导致Cannot locate option with text: broker1 如果我尝试selecByIndex或Value,结果是相同的 - 无法找到该元素。

我已导入org.openqa.selenium.support.ui.Select; 感谢您提供的任何帮助。

我很抱歉让这个变得更复杂...... 我也尝试了oDropdowm.selectByValue("1");,但这也会返回"Cannot locate option with value 1"

2 个答案:

答案 0 :(得分:0)

由于我在此处的HTML代码段中未将“broker1”视为选项,因此错误为Cannot locate option with text: broker1

您可以尝试以下代码按值选择,或者(根据提供的HTML代码段基于代码):

Select oDropdown = new Select(driver.findElement(By.id("ctl00_wnCore_ctrlBrokerSelect_ddlSelectCompany")));
oDropdown.selectByValue("0"); //For selecting option with value '0'
oDropdown.selectByValue("1"); //For selecting option with value '1'
oDropdown.selectByValue("2"); //For selecting option with value '2'

编辑12/01/15

如我所见,“value”属性未更改,因此使用“value”的先前代码将起作用。另外,如果您想按可见文字选择选项,则以下代码应该适合您。

try{
    //waiting 20 seconds to detect the visibility of the dropdown
    WebDriverWait wait = new WebDriverWait(driver, 20);
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ctl00_wnCore_ctrlBrokerSelect_ddlSelectCompany")));

    Select oDropdown = new Select(element);
    oDropdown.selectByVisibleText("Anna Test Company");
}catch(Throwable e){
    System.err.println("Error while waiting for the element to be clickable: "+e.getMessage());
}

答案 1 :(得分:0)

根据您的HTML代码段,option1没有"Broker1"文本。

请提供

selectByVisibleTest("Select Company") 

再试一次。

相关问题