[英]How to get the selected value of a dropdown in C#
如何在下拉列表中获取选定的值
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>
要在下拉列表中获取选定的值,您必须为element_to_be_clickable()
诱导WebDriverWait并且您可以使用以下任一定位器策略:
使用CssSelector :
SelectElement status = new SelectElement(driver.FindElement(By.CssSelector("select[name='appealStatusId']"))); IWebElement selected = status.SelectedOption; Console.Write(selected.Text);
使用XPath :
SelectElement status = new SelectElement(driver.FindElement(By.XPath("//select[@name='appealStatusId']"))); IWebElement selected = status.SelectedOption; Console.Write(selected.Text);
使用名称:
SelectElement status = new SelectElement(driver.FindElement(By.Name("appealStatusId"))); IWebElement selected = status.SelectedOption; Console.Write(selected.Text);
您可以 select 元素在下拉选项中基于它的值、文本或 ID。
通过使用文本:
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();
}
}
或者通过使用 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.