gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:14:55 25 4
gpt4 key购买 nike

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

这是一个例子:

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

最后一行检索包装在 IWebElement 中的 select HTML 元素。

需要一种方法来模拟对该选择列表中特定选项的选择,但我不知道该怎么做.


关于一些research ,我发现人们使用 ISelenium DefaultSelenium 类来完成以下操作的示例,但我没有使用此类,因为我正在使用 IWebDriverINavigation(来自 defaultDriver.Navigate())。

我还注意到 ISelenium DefaultSelenium 包含大量其他方法,这些方法在 IWebDriver 的具体实现中不可用。

那么有什么方法可以将 IWebDriverINavigationISelenium DefaultSelenium 结合使用?

最佳答案

正如 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 对象上有很多方法。 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 也不会存在。 Support 包在 Java 库(PageObject 所在的位置)中具有相对较长的历史,但它在 .Net 驱动程序中仍然很新鲜。幸运的是,从源代码构建真的很容易。我 pulled from SVN然后从 beta 下载中引用 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 api 的方法。 Selenium 2 与 Selenium 1 有很大的不同,因此除非您尝试将旧测试迁移到新的 Selenium 2 api(通常称为 WebDriver api),否则您不会使用 DefaultSelenium。

关于c# - 使用 Selenium 2 的 IWebDriver 与页面上的元素进行交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com