如何在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>

enter image description here

解决方法

您可以在下拉选项中根据其值,文本或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);