使用Selenium WebDriver C#从下拉列表中选择一个值 [英] Select a value from drop down using Selenium WebDriver C#

查看:142
本文介绍了使用Selenium WebDriver C#从下拉列表中选择一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用WebDriver的C#绑定从下拉列表中选择值时,我遇到了困难.我过去既没有使用C#也没有使用WebDriver.我正在将WebDriver-Selenium-dotnet2.0b3与Visual Studio C#2010 Express版一起使用. 我已经将WebDriver.Common,WebDriver.Firefox和WebDriver.Remote添加到了我的解决方案中.我尝试使用此-

I am having tough time in selecting value from drop down using C# binding of WebDriver. I have worked on neither C# nor WebDriver in past. I am using WebDriver - Selenium-dotnet2.0b3 with Visual Studio C# 2010 Express edition. I have added WebDriver.Common, WebDriver.Firefox and WebDriver.Remote to my solution. I tried using this -

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

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

But got to see error, when running my solution in 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]'.

如果我不进行转换,那么甚至将无法构建解决方案. 我想我在这里错过了一些琐碎的事情.谁能指导我在这里? 在Selenium 1.0中下拉菜单曾经很简单:-/

And if I don't cast then would not be able to even build the solution. I guess I am missing some thing trivial here. Any one who could guide me here? Drop down selection used to be so simple in Selenium 1.0 :-/

推荐答案

1)使用已注释的SelectElement-

1) Using a SelectElement as already commented - How to select an option from drop down using Selenium WebDriver C#? The SelectElement belongs to the OpenQA.Selenium.Support.UI namespace.

2)您还可以使用CSS选择器执行以下操作:

2) You could also do something like this with css selectors:

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

这篇关于使用Selenium WebDriver C#从下拉列表中选择一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆