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

时间:2011-01-11 12:12:16

标签: c# unit-testing selenium selenium-iedriver

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

这是一个例子:

IWebDriver defaultDriver = new InternetExplorerDriver();
var ddl = driver.FindElements(By.TagName("select"));

最后一行检索包含在select

中的IWebElement HTML元素

需要一种方法来模拟对option列表中特定select的选择,但我无法弄清楚如何去做。


在一些research之后,我找到了人们正在使用ISelenium DefaultSelenium类来完成以下操作的示例,但我没有使用此类,因为我正在使用{{1}进行所有操作}和IWebDriver(来自INavigation)。

我还注意到defaultDriver.Navigate()包含许多其他方法,这些方法在ISelenium DefaultSelenium的具体实现中不可用。

那么我可以将IWebDriverIWebDriverINavigation结合使用吗?

2 个答案:

答案 0 :(得分: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>

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

        }
    }
}

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

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

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。

答案 1 :(得分:2)

您应该使用optionselect获取所有ddl.FindElements(By.TagName("option"));个元素。然后,您可以使用SetSelected

IWebElement方法遍历返回的集合并选择所需的项目

更新:似乎现在WebDriver中存在Select的C#实现 - 之前它只是在Java中。请查看其code,并且使用此类

更容易
相关问题