正如 ZloiAdun 提到的,OpenQA.Selenium.Support.UI 命名空间中有一个可爱的新 Select 类。这是访问选择元素及其选项的最佳方法之一,因为它的 api 非常简单。假设您有一个看起来像这样的网页
<!DOCTYPE html>
<head>
<title>Disposable Page</title>
</head>
<body >
<select id="select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
您访问选择的代码将如下所示。请注意我如何通过将普通 IWebElement 传递给它的构造函数来创建 Select 对象。 Select 对象有很多方法。看一下源码 http://code.google.com/p/selenium/source/browse/trunk/support/src/csharp/webdriver-support/UI/Select.cs了解更多信息,直到得到正确记录。
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;
using System.Collections.Generic;
using OpenQA.Selenium.IE;
namespace Selenium2
{
class SelectExample
{
public static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("www.example.com");
//note how here's i'm passing in a normal IWebElement to the Select
// constructor
Select select = new Select(driver.FindElement(By.Id("select")));
IList<IWebElement> options = select.GetOptions();
foreach (IWebElement option in options)
{
System.Console.WriteLine(option.Text);
}
select.SelectByValue("audi");
//This is only here so you have time to read the output and
System.Console.ReadLine();
driver.Quit();
}
}
}
不过,关于支持类有几点需要注意。即使您下载了最新的测试版,支持 DLL 也不会存在。支持包在 Java 库(即 PageObject 所在的位置)中具有相对较长的历史,但在 .Net 驱动程序中仍然相当新鲜。幸运的是,从源代码构建它非常容易。我从 SVN 拉取 http://code.google.com/p/selenium/source/checkout然后引用了 Beta 下载中的 WebDriver.Common.dll,并在 C# Express 2008 中构建。该类尚未像其他一些类那样经过良好的测试,但我的示例可以在 Internet Explorer 和 Firefox 中运行。
根据上面的代码,我还应该指出一些其他事情。首先是您用来查找选择元素的行
driver.FindElements(By.TagName("select"));
将会发现all选择元素。你可能应该使用driver.FindElement
,没有's'。
此外,您很少会直接使用 INavigation。您将像这样完成大部分导航driver.Navigate().GoToUrl("http://example.com");
Lastly, DefaultSelenium
是访问旧版 Selenium 1.x api 的方法。 Selenium 2 与 Selenium 1 有很大的不同,因此除非您尝试将旧测试迁移到新的 Selenium 2 api(通常称为 WebDriver api),否则您不会使用 DefaultSelenium。