如何使用 Selenium WebDriver C# 从下拉列表中选择一个选项? [英] How to select an option from drop down using Selenium WebDriver C#?

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

问题描述

我正在尝试为我的网络测试选择一个选项.可以在此处找到示例:http://www.tizag.com/phpT/examples/formex.php

I was trying for my web test selecting an option. An example can be found here: http://www.tizag.com/phpT/examples/formex.php

除了选择一个选项部分外,一切都很好.如何按值或按标签选择选项?

Everything works great except the selecting an option part. How to selecting an option by value or by label?

我的代码:

using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

class GoogleSuggest
{
    static void Main()
    {
        IWebDriver driver = new FirefoxDriver();

        //Notice navigation is slightly different than the Java version
        //This is because 'get' is a keyword in C#
        driver.Navigate().GoToUrl("http://www.tizag.com/phpT/examples/formex.php");
        IWebElement query = driver.FindElement(By.Name("Fname"));
        query.SendKeys("John");
        driver.FindElement(By.Name("Lname")).SendKeys("Doe");
        driver.FindElement(By.XPath("//input[@name='gender' and @value='Male']")).Click();
        driver.FindElement(By.XPath("//input[@name='food[]' and @value='Chicken']")).Click();
        driver.FindElement(By.Name("quote")).Clear();
        driver.FindElement(By.Name("quote")).SendKeys("Be Present!");
        driver.FindElement(By.Name("education")).SendKeys(Keys.Down + Keys.Enter); // working but that's not what i was looking for
        // driver.FindElement(By.XPath("//option[@value='HighSchool']")).Click(); not working
        //  driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr/td/div[5]/form/select/option[2]")).Click(); not working
        // driver.FindElement(By.XPath("id('examp')/x:form/x:select[1]/x:option[2]")).Click(); not working

        }
}

推荐答案

您必须从下拉列表中创建一个选择元素对象.

You must create a select element object from the drop down list.

 using OpenQA.Selenium.Support.UI;

 // select the drop down list
 var education = driver.FindElement(By.Name("education"));
 //create select element object 
 var selectElement = new SelectElement(education);

 //select by value
 selectElement.SelectByValue("Jr.High"); 
 // select by text
 selectElement.SelectByText("HighSchool");

更多信息这里

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

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