【问题标题】:Selenium - Not able to select option from drop downSelenium - 无法从下拉列表中选择选项
【发布时间】:2015-03-13 12:24:08
【问题描述】:

以下是代码:

public static void test1() {  
System.out.print("\nTo find UserName element");
Select select = new Select(driver.findElement(By.id("drop_down")));
System.out.print("\nElements found");
select.selectByIndex(1);
}

以下都不是:

select.selectByIndex(1);
select.selectByValue("1");
select.selectByVisibleText("Super Admin"); 

它抛出一个异常: 线程“主”org.openqa.selenium.NoSuchElementException 中的异常:无法找到具有值的选项:1

<select id="drop_down" style="width:205px;" name="drop_down">
    <option value=""></option>
    <option value="1">
        Super Admin
    </option>
    <option value="4">
        Question Reviewer
    </option>
    <option value="6">
    Evaluator
    </option>
</select>

【问题讨论】:

  • 下拉列表的值是根据输入的电子邮件填充的。

标签: select selenium drop-down-menu


【解决方案1】:

当您尝试访问下拉菜单时,可能没有正确加载它

尝试下面的代码等到下拉列表中的选项数量大于1,然后从中选择第一个选项

try{
    // Waits for 20 seconds
    WebDriverWait wait = new WebDriverWait(driver, 20);

    // Wait until expected condition size of the dropdown increases and becomes more than 1
    wait.until((ExpectedCondition<Boolean>) new ExpectedCondition<Boolean>(){
        public Boolean apply(WebDriver driver)  
        {
            Select select = new Select(driver.findElement(By.id("drop_down")));
            return select.getOptions().size()>1;
        }
    });

    //To select the first option
    Select select = new Select(driver.findElement(By.id("drop_down")));
    select.selectByVisibleText("Super Admin");
}catch(Throwable e){
    System.out.println("Error found: "+e.getMessage());
}

【讨论】:

  • 仍然收到相同的错误:无法找到带有文本的元素:超级管理员
  • 我必须选择超级管理员。
  • 好的..你能不能在输入电子邮件地址之前添加下拉列表的HTML sn-p,正如你所说的“下拉列表的值是根据输入的电子邮件填充的”?然后我会相应地修改我的代码,
  • 另外,上面 html 的 sn-p 中的名称类似于 drop_down[index]
【解决方案2】:

嗨,根据 1 月 15 日 6:35 的第一条评论 bu Subh,我也修改了代码,但得到了与 Abhinav 在 1 月 15 日 6:53 提到的相同的错误,之后 Subh 说“我已经编辑了上面的代码..看看它是否适合你,请让我知道,请..”但在此评论之后我没有看到任何修改过的代码,因此这没有帮助..最后我搜索了几个其他论坛并尝试了使用selectByIndex() 作为:-

WebElement toactTyp=driver1.findElement(By.name((<Name of the Element to access>)));
Select toactSel=new Select(toactTyp);
toactSel.selectByIndex(2);

上面的代码效果很好.....我要求分享修改后的代码或至少修改完成的行,因为它对像我这样的很多人很有用

【讨论】:

  • 差不多 2 年后。抱歉回复晚了.. :) 实际上我确实修改了代码。早些时候,它只是等待下拉菜单出现,然后选择相关选项。在 OP 回复后,确认该应用程序正在使用 ajax 在输入电子邮件地址时加载选项。因此,我修改了代码以等到选项计数>1,然后是selectByVisibleText,其中我可以使用selectByindex 并给出'1',这样也可以。出于正常目的,您的代码当然是预期的,因为您的代码是下拉选项不变的情况。
猜你喜欢
  • 2022-12-15
  • 1970-01-01
  • 2016-10-13
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多