如何解决如何在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>
解决方法
您可以在下拉选项中根据其值,文本或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");
,
要在下拉列表中获取选定的值,您必须为element_to_be_clickable()
引入WebDriverWait,并且可以使用以下Locator Strategies中的任何一个:
-
使用 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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。