使用Selenium 2的IWebDriver与页面上的元素进行交互

And*_*ech 6 c# selenium unit-testing selenium-iedriver

我正在使用Selenium IWebDriver来编写C#中的单元测试.

这是一个例子:

IWebDriver defaultDriver = new InternetExplorerDriver();
var ddl = driver.FindElements(By.TagName("select"));
Run Code Online (Sandbox Code Playgroud)

最后一行检索包含在中的selectHTML元素IWebElement.

需要一种方法来模拟选择到optionselect列表中的特定但我无法弄清楚如何做到这一点.


在一些研究中,我发现那里的人正在使用的实例ISelenium DefaultSelenium类来完成以下,但因为我做的一切,我不会使这个类的使用IWebDriverINavigation(来自defaultDriver.Navigate()).

我还注意到,ISelenium DefaultSelenium其中包含大量其他方法,这些方法在具体实现中没有IWebDriver.

那么我有什么方法可以使用IWebDriverINavigation与之结合使用ISelenium DefaultSelenium

pne*_*ook 8

正如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>
Run Code Online (Sandbox Code Playgroud)

你访问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<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();

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是有关支持类的一些注意事项.即使您下载了最新的测试版,支持DLL也不会存在.支持包在Java库中有相对较长的历史(这是PageObject所在的历史),但在.Net驱动程序中它仍然很新鲜.幸运的是,从源代码构建起来非常容易.我从SVN中提取然后从测试版下载中引用了WebDriver.Common.dll并在C#Express 2008中内置.这个类没有像其他一些类那样经过测试,但我的例子在Internet Explorer和Firefox中工作.

根据上面的代码,我应该指出一些其他的事情.首先是您用来查找select元素的行

driver.FindElements(By.TagName("select"));
Run Code Online (Sandbox Code Playgroud)

将找到所有选择元素.你应该使用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.