我是 C# 和 Selenium WebDriver 的新手。
我知道如何选择/单击下拉列表中的选项,但在此之前我遇到了问题。由于下拉列表是动态生成的,我必须在运行每个案例之前从列表中获取所有选项/值。
有没有人告诉我如何从下拉列表中获取所有值/选项。我正在使用 IE,但我没有找到任何类支持在 C# 的 Selenium.IE 命名空间中获取值/选项的方法。
我的例子: 一个列表包含多个时区:
<TD>
<select name = "time_zone">
<option value "-09:00"><script>timezone.Alaska</script></option>
<option value "+00:00"><script>timezone.England</script></option>
<option value "+02:00"><script>timezone.Greece</script></option>
<option value "+05:30"><script>timezone.India</script></option>
</select>
<TD>
这是一个IE页面的下拉列表,如何获取动态生成的时区列表?
我的代码:
IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
List<IWebElement> options = elem.FindElements(By.TagName("option"));
C# 只是弹出一个错误: 无法将类型“OpenQA.Selenium.IWebElement”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少转换?)。
谢谢。
最佳答案
您可以尝试使用 OpenQA.Selenium.Support.UI.Selected 命名空间中的 WebDriver.Support SelectElement 来访问选择列表的选项列表:
IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;
然后您可以将每个选项作为 IWebElement 访问,例如:
IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");
关于c# - 如何使用 C# 通过 Selenium WebDriver 获取下拉列表中的所有选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9562853/