简体   繁体   中英

How do I find and select a dropdown value with Selenium using C# in Visual Studio 2017

I am trying to locate an element within a dropdown list with Selenium. How can I do this? Attached are images which describe the situation. I want to do this using the IWebElement function.

I've tried using the following:

IWebElement Depart = driver.FindElement(By.XPath("///input[@name='fromPort' and @value='Sydney']"));

but it does not work!! How can I select Sydney from the drop-down list?

在此处输入图片说明

If the dropdown is defined with select and option tag, then you can use the SelectElement class to select the value from the dropdown.

You can use any one of the method to select the value from the dropdown Refer the Documentation

SelectByIndex - Select an option by the index

SelectByText - Select an option by the text displayed.

SelectByValue - Select an option by the value.

You need to pass the dropdown element to the SelectElement class and can use any one of the above method

Code:

IWebElement Depart = driver.FindElement(By.Name("fromPort"));
SelectElement select=new SelectElement(Depart);

Option 1:

 select.SelectByText("Sydney");

Option 2:

 select.SelectByValue("Sydney");

Option 3:

 select.SelectByIndex(8);//Sydney value index is 8

Use the following code for that:

using OpenQA.Selenium.Support.UI;


var selectElement = new SelectElement(driver.FindElement(By.Name("fromPort")));
selectElement.SelectByText("London");

Hope it helps you!

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