使用Selenium WebDriver C#在下拉列表中选择每个选项

我无法在下拉列表中选择选项。 我想我需要.SelectSelectElement ,但没有这样的选择。

示例代码:

 IWebDriver ffbrowser = new FirefoxDriver(); ffbrowser.Navigate().GoToUrl("http://www.amazon.com/"); ffbrowser.Manage().Window.Maximize(); Thread.Sleep(500); IWebElement ddl = ffbrowser.FindElement(By.Name("url")); int numofitems = ddl.FindElements(By.TagName("option")).Count; for (int i = 1; i < numofitems; i++) { ffbrowser.select("TagName = option", "index = i"); } 

“ffbrowser.select”中的“select”报告为错误:

错误1’OpenQA.Selenium.IWebDriver’不包含’select’的定义,并且没有扩展方法’select’接受类型’OpenQA.Selenium.IWebDriver’的第一个参数可以找到(你是否缺少using指令或者assembly参考?)

我的项目参考包括Selenium.WebDriverBackedSeleniumThoughtworks.Selenium.CoreWebDriverWebDriver.Support

我有

 using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.IE; using OpenQA.Selenium.Support.UI; 

根据您使用的Selenium WebDriver的版本,您可以使用SelectElement类,该类将包含在OpenQA.Selenium.Support.UI
例如:

 SelectElement selector = new SelectElement(element); selector.SelectByIndex(1); 

元素是你的下拉框。

下面是一个示例,可以更好地说明如何获取下拉列表中的所有项目以及从下拉列表中选择项目。

下拉列表的示例Html代码

  

下面的代码从上面的下拉列表中获取所有项目,并选择项目’Coffee’。代码的逻辑如下

步骤1.创建web元素标记的接口步骤2.使用web元素标记的所有子元素创建IList步骤3.选择Drop List项“Coffee”

 using System; using System.Collections.Generic; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace SeleniumTests { class DropDownListSelection { static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://DropDownList.html"); IWebElement element = driver.FindElement(By.XPath("//Select")); IList AllDropDownList = element.FindElements(By.XPath("//option")); int DpListCount = AllDropDownList.Count; for (int i = 0; i < DpListCount; i++) { if (AllDropDownList[i].Text == "Coffee") { AllDropDownList[i].Click(); } } Console.WriteLine(DpListCount); Console.ReadLine(); } } } 

您还可以使用:

 new SelectElement(driver.FindElement(By.Id("")).SelectByText("")); 

要么:

 new SelectElement(driver.FindElement(By.Id("")).SelectByValue("")); 

使用以下简单的示例代码:

 String Input="Value to Select"; String xPathVal="@["id=Samplexpath"]"; IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal)); SelectElement dropdown = new SelectElement(TargetElement); dropdown.SelectByText(Input.Trim()); 

这很完美……

 SelectElement selector = new SelectElement(element); selector.SelectByIndex(1); 

元素是你的下拉框。