c# – 使用Selenium 2的IWebDriver与页面上的元素进行交互
我正在使用Selenium的IWebDriver在C#中编写单元测试.
这是一个例子: IWebDriver defaultDriver = new InternetExplorerDriver(); var ddl = driver.FindElements(By.TagName("select")); 最后一行检索包含在IWebElement中的select HTML元素. 我需要一种方法来模拟选择列表中的特定选项,但我无法弄清楚如何做到这一点. 大约research,我找到了人们使用ISelenium DefaultSelenium类来完成以下操作的示例,但我没有使用这个类,因为我正在使用IWebDriver和INavigation(来自defaultDriver.Navigate()). 我还注意到ISelenium DefaultSelenium包含许多其他方法,这些方法在IWebDriver的具体实现中不可用. 那么有什么方法可以将IWebDriver和INavigation与ISelenium DefaultSelenium结合使用? 解决方法
正如ZloiAdun所提到的,OpenQA.Selenium.Support.UI命名空间中有一个可爱的新类.这是访问选择元素的最佳方式之一,它的选项因为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> 你访问select的代码看起来像这样.注意我如何通过将普通的IWebElement传递给它的构造函数来创建Select对象. Select对象上有很多方法. Take a look at the source获取更多信息,直到获得正确记录. 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驱动程序中它仍然很新鲜.幸运的是,从源代码构建起来非常容易.我pulled from 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |