Selenium: How to wait for options in a select to be populated?

半城伤御伤魂 提交于 2019-11-28 23:18:15

I think you should be use

waitForElementPresent command. If possible let's me see your selenium IDE code.

I used waitForElementPresent with a css target.

Example: To wait for

<select id="myselect"></select>

to be populated with

<option value="123">One-two-three</option>

use

  • Command: waitForElementPresent
  • Target: css=#myselect option[value=123]
  • Value: (leave it empty)

You can use "WaitForSelectOption" command where your value can be direct label like label=1-saving Account target will have the object id

Radek Porazil

I found handy something like:

wait.until(
    ExpectedConditions
        .presenceOfNestedElementsLocatedBy(By.id(<selectioNId>), By.tagName("option"))
)

I made the following function in C# that returns the select when is populated.

You have to pass a By to find the element and you a specific time to wait for it to be filled:

public static SelectElement FindSelectElementWhenPopulated(this IWebDriver driver, By by, int delayInSeconds)
    {
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(delayInSeconds));
        return wait.Until<SelectElement>(drv => 
        {
            SelectElement element = new SelectElement(drv.FindElement(by));
            if (element.Options.Count >= 2)
            {
                return element;
            }

            return null;
        }
        );
    }

In my case I validate tha the select has more than 2 options, you can change the code so that it validates the quantity that fits your needs.

We had similar problem where the options within drop down was fetched from a third party service, which sometimes was a slower operation.

Select select = new Select(driver.findElement(cssSelector("cssSelectorOfSelectBox")));    
waitUnitlSelectOptionsPopulated(select)

here is the definition for waitUnitlSelectOptionsPopulated

private void waitUntilSelectOptionsPopulated(final Select select) {
            new FluentWait<WebDriver>(driver)
                    .withTimeout(60, TimeUnit.SECONDS)
                    .pollingEvery(10, TimeUnit.MILLISECONDS)
                    .until(new Predicate<WebDriver>() {
                        public boolean apply(WebDriver d) {
                            return (select.getOptions().size() > 1);
                        }
                    });
        }

Note: A check of select.getOptions().size() >1 was needed in our case as we had one static option always displayed.

ibenjelloun

Using java 8 Awaitility

Awaitility.await()
.atMost(5, TimeUnit.SECONDS)
.until(() -> select.getOptions().size() > 0);

Its work for me:

  WebElement element = driver.findElement(By.xpath("//select[@name='NamE']/option[1]"));
  return element.getAttribute("text");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!