[英]How to get the selected value of a dropdown in C#
How do I get the selected value in the dropdown如何在下拉列表中获取选定的值
HTML Code: HTML 代码:
<select name="appealStatusId" class="form-control input-sm">
<option value="1">
Pending
</option>
<option value="2">
Overall Appeal Approved
</option>
<option value="3" selected="selected">
Overall Appeal Not Approved
</option>
To get the selected value in the dropdown you have to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following Locator Strategies :要在下拉列表中获取选定的值,您必须为element_to_be_clickable()
诱导WebDriverWait并且您可以使用以下任一定位器策略:
Using CssSelector :使用CssSelector :
SelectElement status = new SelectElement(driver.FindElement(By.CssSelector("select[name='appealStatusId']"))); IWebElement selected = status.SelectedOption; Console.Write(selected.Text);
Using XPath :使用XPath :
SelectElement status = new SelectElement(driver.FindElement(By.XPath("//select[@name='appealStatusId']"))); IWebElement selected = status.SelectedOption; Console.Write(selected.Text);
Using Name :使用名称:
SelectElement status = new SelectElement(driver.FindElement(By.Name("appealStatusId"))); IWebElement selected = status.SelectedOption; Console.Write(selected.Text);
You can select the element based on it's Value, Text or Id in dropdown options.您可以 select 元素在下拉选项中基于它的值、文本或 ID。
By using text:通过使用文本:
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("your_URL");
driver.Manage().Window.Maximize();
IWebElement element_name = driver.FindElement(By.Name("appealStatusId"));
SelectElement statusId = new SelectElement(element_name);
// To print all available options
Console.WriteLine(statusId.Options);
// To iterate over the dropdown options and select the one which matches with the text you want to select
foreach(IWebElement element in statusId.Options)
{
if(element.Text == "Overall Appeal Not Approved")
{
element.Click();
}
}
Or by using SelectByValue:或者通过使用 SelectByValue:
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("your_URL");
driver.Manage().Window.Maximize();
IWebElement element_name = driver.FindElement(By.Name("appealStatusId"));
SelectElement statusId = new SelectElement(element_name);
statusId.SelectByValue("3");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.