Selenium - Not able to select option from drop down

痞子三分冷 提交于 2020-01-05 13:12:30

问题


Following is the code:

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);
}

Neither following wroks:

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

It throws an exception: Exception in thread "main" org.openqa.selenium.NoSuchElementException: Cannot locate option with value: 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>

回答1:


May be the dropdown is not properly loaded, when you try to access it.

Try the below code to wait till the number of options in the dropdown becomes greater than 1, and then select the first option from it:

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());
}



回答2:


Hi as per the first comment bu Subh on Jan 15 at 6:35 I too modified the code but getting the same error as mentioned by Abhinav on Jan 15 at 6:53 after that Subh said "I have edited my code above.. See if it works out for you and let me know too, please.." but I didn't see any modified code after this comment hence this didn't help....finally I searched few other forums and I tried using selectByIndex() as:-

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

It worked well with the above code.....I request to please share the modified code or atleast the lines where the modification has been done as it useful to a lot like me



来源:https://stackoverflow.com/questions/27957851/selenium-not-able-to-select-option-from-drop-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!