简体   繁体   中英

Selecting Options from a Drop Down Menu in C# using Selenium

I am trying to select a specific option in a drop down menu. My current code highlights the selection I want, but moves on and does not keep the value in the field after "selecting" it. I want to grab the value "Medical." Currently I am using:

IWebElement element = driver.FindElement(By.Name("DISPLAY_CoverageType"));
SelectElement selector = new SelectElement(element);
selector.SelectByText("Medical");

The List I am pulling from looks like:

<option value="">Please Select One</option>
<option value="Medical">Medical</option>
<option value="Hospital">Hospital</option>
<option value="Dental">Dental</option>
<option value="Vision">Vision</option>

This highlights my selection in blue, but does not keep it selected when the drop down menu closes. Any advice?

You can also use css selector to bypass the SelectElement class and find the option directly.

string option = "Medical";
By css = By.CssSelector("Select>option[value='" + option + "']");
driver.FindElement(css).Click();

Use below line

 selector.selectByValue("Medical"); 

Instead of

 selector.SelectByText("Medical");

Let me know is it working or not.

Apparently going the repetitive and "easy" route was the correct way the entire time. This code helped me pass my tests:

driver.FindElement(By.Name("DISPLAY_CoverageType")).Click();
driver.FindElement(By.XPath("//td[4]/select/option[3]")).Click();
driver.FindElement(By.XPath("//td[4]/select/option[3]")).Click();

Thanks to @alecxe for the idea of repeating calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM