使用Selenium WebDriver C#从下拉列表中选择一个值

Tar*_*run 9 c# webdriver selenium-webdriver

我正在艰难地使用WebDriver的C#绑定从下拉列表中选择值.我过去既没有使用C#也没有使用WebDriver.我正在使用WebDriver - Selenium-dotnet2.0b3和Visual Studio C#2010 Express版.我已将WebDriver.Common,WebDriver.Firefox和WebDriver.Remote添加到我的解决方案中.我试过用这个 -

IWebElement dateOfBirth = webdriver.FindElement(By.Id("join_birth_day"));
List<IWebElement> dateOfBirthOptions = (List<IWebElement>)dateOfBirth.FindElement(By.TagName("option"));

foreach(IWebElement dateOfBirthOption in dateOfBirthOptions)  
{
    if (dateOfBirthOption.Equals("3"))
    {
        dateOfBirthOption.Select();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是在NUnit中运行我的解决方案时,必须看到错误

LiveCams.CreateAccount.createAccount:
System.InvalidCastException : Unable to cast object of type 'OpenQA.Selenium.Firefox.FirefoxWebElement' to type 'System.Collections.Generic.List`1[OpenQA.Selenium.IWebElement]'.
Run Code Online (Sandbox Code Playgroud)

如果我不投,那么甚至无法构建解决方案.我想我在这里错过了一些微不足道的事情.谁能指导我在这里?在Selenium 1.0中,下拉选择过于简单: - /

小智 9

要从下拉列表中选择选项,请使用以下代码

  1. 要根据文本选择值

    new SelectElement(driver.FindElement(By.XPath(""))).SelectByText("");
    
    Run Code Online (Sandbox Code Playgroud)
  2. 要根据值选择值

    new SelectElement(driver.FindElement(By.XPath(""))).SelectByValue("");
    
    Run Code Online (Sandbox Code Playgroud)
  3. 要根据索引选择值

    new SelectElement(driver.FindElement(By.XPath(""))).SelectByIndex(0);
    
    Run Code Online (Sandbox Code Playgroud)


Mat*_*lly 7

1)使用已注释的SelectElement - 如何使用Selenium WebDriver C#从下拉列表中选择一个选项? SelectElement属于OpenQA.Selenium.Support.UI命名空间.

2)你也可以用css选择器做这样的事情:

WebElement dateOfBirth =  webdriver.FindElement(By.Id("join_birth_day"))
                              .FindElement(By.CssSelector("option[value='3']")).Select();
Run Code Online (Sandbox Code Playgroud)

  • 我无法获得SelectElement的引用,我错过了任何DLL吗? (2认同)