使用Selenium 2的IWebDriver与页面上的元素进行交互
我正在使用Selenium的IWebDriver
在C#中编写unit testing。
这是一个例子:
IWebDriver defaultDriver = new InternetExplorerDriver(); var ddl = driver.FindElements(By.TagName("select"));
最后一行检索包含在IWebElement
的select
HTML元素。
我需要一种方法来模拟select
列表中的特定option
,但我无法弄清楚如何做到这一点。
经过一些研究 ,我找到了人们使用ISelenium DefaultSelenium
类来完成以下操作的ISelenium DefaultSelenium
,但我没有使用这个类,因为我正在使用IWebDriver
和INavigation
(来自defaultDriver.Navigate()
)。
我还注意到ISelenium DefaultSelenium
包含许多其他方法,这些方法在IWebDriver
的具体实现中IWebDriver
。
那么有什么方法可以将IWebDriver
和INavigation
与ISelenium DefaultSelenium
结合使用?
正如ZloiAdun所提到的,OpenQA.Selenium.Support.UI命名空间中有一个可爱的新类。 这是访问选择元素的最佳方式之一,它的选项因为api非常简单。 假设你有一个看起来像这样的网页
Disposable Page
你访问select的代码看起来像这样。 注意我是如何通过将普通的IWebElement传递给它的构造函数来创建Select对象的。 Select对象上有很多方法。 查看源代码以获取更多信息,直到获得正确记录。
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 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也不会存在。 Support包在Java库中有相对较长的历史(这是PageObject所在的历史),但在.Net驱动程序中它仍然很新鲜。 幸运的是,从源代码构建起来非常容易。 我从SVN撤出然后从测试版下载中引用了WebDriver.Common.dll并在C#Express 2008中内置。这个类没有像其他一些类那样经过良好测试,但我的示例在Internet Explorer和Firefox中有效。
根据上面的代码,我应该指出一些其他的事情。 首先是您用来查找select元素的行
driver.FindElements(By.TagName("select"));
将找到所有选择元素。 你应该使用driver.FindElement
,而不是’s’。
此外,您很少直接使用INavigation。 您将完成大部分导航,例如driver.Navigate().GoToUrl("http://example.com");
最后, DefaultSelenium
是访问旧版Selenium 1.x apis的方法。 Selenium 2与Selenium 1有很大的不同,所以除非你试图将旧的测试迁移到新的Selenium 2 api(通常称为WebDriver api),否则你不会使用DefaultSelenium。
您应该使用ddl.FindElements(By.TagName("option"));
从select
获取所有option
元素ddl.FindElements(By.TagName("option"));
。 然后,您可以遍历返回的集合,并使用IWebElement
SetSelected
方法选择所需的项目
更新 :似乎现在有一个Select
in WebDriver的C#实现 – 以前只用Java。 请看一下它的代码 ,这个类更容易使用