C# 使用Selenium 2的IWebDriver与页面上的元素交互
我正在使用Selenium的IWebDriver用C编写单元测试 例如:C# 使用Selenium 2的IWebDriver与页面上的元素交互,c#,unit-testing,selenium,selenium-iedriver,C#,Unit Testing,Selenium,Selenium Iedriver,我正在使用Selenium的IWebDriver用C编写单元测试 例如: IWebDriver defaultDriver = new InternetExplorerDriver(); var ddl = driver.FindElements(By.TagName("select")); 最后一行检索包装在IWebElement中的select HTML元素 我需要一种方法来模拟选择列表中特定选项的选择,但我不知道如何做 在一些例子中,我发现人们正在使用ISelenium DefaultS
IWebDriver defaultDriver = new InternetExplorerDriver();
var ddl = driver.FindElements(By.TagName("select"));
最后一行检索包装在IWebElement中的select HTML元素
我需要一种方法来模拟选择列表中特定选项的选择,但我不知道如何做
在一些例子中,我发现人们正在使用ISelenium DefaultSelenium类来完成以下任务,但我没有使用这个类,因为我正在使用IWebDriver和defaultDriver.Navigate中的INavigation完成所有工作
我还注意到ISelenium DefaultSelenium包含大量其他方法,这些方法在IWebDriver的具体实现中是不可用的
那么,我有没有办法将IWebDriver和iVigation与ISelenium DefaultSelenium结合使用?您应该使用ddl.FindElementsBy.TagNameoption;从select中获取所有选项元素;。然后,您可以使用IWebElement的SetSelected方法遍历返回的集合并选择所需的项
更新:现在似乎在WebDriver中有了Select的C实现——以前它只在Java中实现。请看一下它的名称空间,使用这个类更容易,正如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>
将查找所有选定元素。您可能应该使用driver.FindElement,而不使用“s”
此外,很少会直接使用INavigation。您将执行大部分导航操作,如driver.Navigate.GoToUrlhttp://example.com;
最后,DefaultSelenium是访问旧的Selenium 1.x API的方法。Selenium 2与Selenium 1有很大的不同,因此除非您尝试将旧测试迁移到新的Selenium 2 api(通常称为WebDriver api),否则您不会使用DefaultSelenium。IWebElement没有选择的方法。有一个名为Select的方法,但对我来说,它什么都不做。我没有使用C,所以我可能会错过方法的名称-很抱歉。您是否尝试过使用OpenQA.Selenium.Support.UI.Select类?您是否使用了Select选项上的Select?+1由ZloiAdun链接的Select类完成了这项工作,但我接受这个答案,因为您提供了更多信息。因为Select在公共dll中还不可用,所以我目前正在使用ZloiAdun链接的类和异常。至于FindElements,我需要使用它,因为我要检索的select不止一个。最后,感谢您提及有关DefaultSelenium的问题,尽管我有一个后续问题;有没有办法利用DefaultSelenium提供的大量方法?+1来澄清IWebDriver是使用2.x的方式。刚开始,我能找到的大多数演示都使用DefaultSelenium。
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();
}
}
}
driver.FindElements(By.TagName("select"));