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

时间:2013-03-20 21:27:28

标签: c# selenium

我无法在下拉列表中选择选项。我想我需要.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'的第一个参数可以找到(你是否错过了使用指令或程序集引用?)

我的项目参考包括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;

5 个答案:

答案 0 :(得分:26)

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

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

元素是您的下拉框。

答案 1 :(得分:1)

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

下拉列表的示例Html代码

<select>
  <option>Milk</option>
  <option>Coffee</option>
  <option>Tea</option>
</select>

下面的代码从上面的下拉列表中获取所有项目并选择项目'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<IWebElement> 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();
        }
    }
}

答案 2 :(得分:1)

您也可以使用:

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

或者:

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

答案 3 :(得分:0)

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

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());

答案 4 :(得分:0)

这很有效......

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

元素是你的下拉框。