使用C#的Selenium WebDriver-如何从下拉列表中获取所有选项值?

时间:2019-03-06 18:21:31

标签: selenium

我是Selenium WebDriver和Visual Studio 2017的初学者,我需要以下方面的帮助: 从下拉列表中获取所有选项值,然后在控制台中将其打印出来。

<select id="FilterOrganization" name="FilterOrganization" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"><option value="">Show All Organizations</option>
<option value="0013000000H9TkiAAF"> Associates, LLC</option>
<option value="0018000000ubNRhAAM">Test Health Systems</option>
</select>

这是我尝试过的:

driver.FindElement(By.Id("org - list")).Click(); 
SelectElement organization = new SelectElement(driver.FindElement(By.Id("FilterOrganization"))); 
IList<IWebElement> options = organization.AllSelectedOptions; 
foreach (IWebElement option in options)
{ 
    console.writeLine(option.Text) 
} 

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以这样抓住他们

var options = Driver.FindElements(By.CssSelector("select > option"));
var optionValues = options.Select(elem => elem.GetAttribute("value")).ToList();

答案 1 :(得分:0)

我建议安装Selenium.Support nuget,然后您可以执行以下操作:

using OpenQA.Selenium.Support.UI;


// select the drop down list
var element = driver.FindElement(By.Id("FilterOrganization"));
//create select element object 
var selectElement = new SelectElement(element);

foreach (var option in selectElement.Options)
{ 
    Console.WriteLine(option.Text) 
}