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

问题描述 投票:-1回答:2

我是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) 
} 

谢谢!

selenium
2个回答
0
投票

你可以像这样抓住它们

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

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) 
} 
© www.soinside.com 2019 - 2024. All rights reserved.