bytedev
bytedev

Reputation: 9099

Selecting a particular drop down menu list item in Selenium web driver

I'm trying to select a particular option from a select drop down list using .NET Selenium web driver (the options will then be posted as part of the form submission).

I'm currently trying the following (which works when I step through the code - i.e. the option seems to get selected in the web browser, but as soon as I execute the code for real the selecting of the option fails to work):

selectWebElement.Click();
selectWebElement.FindElement(By.XPath("//option[text() = '" + text + "']")).Click();

Do I need some sort of Wait in my code? Does anyone know a bullet proof way of doing this?

UPDATE:

Since posting this I have learned that a more elegant way to set the selected option by it's text is:

new SelectElement(selectWebElement).SelectByText(text);

However, this does not appear to fix the problem. Another thing I did not mention before was that the form is actually inside an iFrame and I'm using the following to switch to it:

WebDriver.SwitchTo().Frame(iframeElement);

Not sure if the fact its in an iframe would cause a problem but I can successfully get a reference to the select element. (The form also has a number of text input elements that I can successfully get to and set etc.)

Upvotes: 3

Views: 2366

Answers (2)

Nayan
Nayan

Reputation: 316

Instead of explicitly click on the drop-down, just use webdriver API call as follows:

selectWebElement.selectByVisibleText("");

or

selectWebElement.selectByIndex();

or

selectWebElement.selectByValue("");

Upvotes: 1

SDET
SDET

Reputation: 1290

Yes, you will probably need to add a short wait between the steps as it takes a small period of time for the dropdown to animate and be fully displayed. If the second click occurs too quickly this can cause a failure.

A simple fixed wait period of, say, one second should work. You could explicitly wait for the animation to complete but in the simple case of dropdowns a short fixed wait should suffice.

Upvotes: 0

Related Questions