问题
HTML:
<select name="ddlFruit" id="ddlFruit" class="Searchddl">
<option value="">Select</option>
<option value="447">Grapes</option>
<option value="448">Mango</option>
<option selected="selected" value="449">Apple</option>
</select>
Suppose "Apple" is in first selected mode, due to some other actions on site, this drop-down changes to other options automatically. I want webdriver to wait until "Mango" text is in selected mode.
Tried code:
public static SelectElement FindSelectElementWhenPopulated(IWebDriver driver, By by, int delayInSeconds, string optionText)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(delayInSeconds));
return wait.Until<SelectElement>(drv =>
{
SelectElement element = new SelectElement(drv.FindElement(by));
if (element.SelectedOption.ToString().Contains(optionText))
{
return element;
}
return null;
}
);
}
Myclass.FindSelectElementWhenPopulated(driver, By.CssSelector("#ddlFruit"), 20, "Mango");
I am using C#.
回答1:
You don't want to convert the SelectedOption
to a string. Test the Text
property instead:
if (element.SelectedOption.Text.Contains(optionText))
With a few changes, you can make this a handy extension method on WebDriverWait:
public static SelectElement UntilOptionIsSelected(this WebDriverWait wait, By by, string optionText)
{
return wait.Until<SelectElement>(driver =>
{
var element = new SelectElement(driver.FindElement(by));
if (element.SelectedOption.Text.Contains(optionText))
{
return element;
}
return null;
});
}
And to use it:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
var dropdown = wait.UntilOptionIsSelected(By.CssSelector("#ddlFruit"), "Mango");
回答2:
You need to use the Select
class in Selenium:
Select dropdowns=new Select(driver.findelement(By.id("ddlFruit")));
dropdowns.selectByVisibleText("Mango");
来源:https://stackoverflow.com/questions/63072700/how-to-wait-until-dropdown-selected-text-matches-other-text-using-selenium