【问题标题】:How to select an option from drop down using Selenium WebDriver C#?如何使用 Selenium WebDriver C# 从下拉列表中选择一个选项?
【发布时间】:2011-07-13 19:00:41
【问题描述】:

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

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

我的代码:

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

        }
}

【问题讨论】:

    标签: c# webdriver selenium-webdriver


    【解决方案1】:

    补充一点——我遇到了一个问题,即在将 Selenium.NET 绑定安装到 C# 项目后,OpenQA.Selenium.Support.UI 命名空间不可用。后来发现我们可以通过运行命令轻松安装最新版本的 Selenium WebDriver Support Classes:

    Install-Package Selenium.Support
    

    在 NuGet 包管理器控制台中,或从 NuGet 管理器安装 Selenium.Support。

    【讨论】:

      【解决方案2】:
      IWebElement element = _browserInstance.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 == "nnnnnnnnnnn")
          {
              AllDropDownList[i].Click();
              _browserInstance.ScreenCapture("nnnnnnnnnnnnnnnnnnnnnn");
          }
      }
      

      【讨论】:

      • 适用于下拉列表选择
      【解决方案3】:
       var select = new SelectElement(elementX);
       select.MoveToElement(elementX).Build().Perform();
      
        var click = (
             from sel in select
             let value = "College"
             select value
             );
      

      【讨论】:

      • 请在您的代码中添加解释:为什么它是问题的答案,以及 它与之前给出的答案有何不同
      【解决方案4】:

      用于从下拉菜单中选择项目的 Selenium WebDriver C# 代码:

      IWebElement EducationDropDownElement = driver.FindElement(By.Name("education"));
      SelectElement SelectAnEducation = new SelectElement(EducationDropDownElement);
      

      选择下拉项有 3 种方式:i)按文本选择 ii)按索引选择 iii)按值选择

      按文本选择:

      SelectAnEducation.SelectByText("College");//There are 3 items - Jr.High, HighSchool, College
      

      按索引选择:

      SelectAnEducation.SelectByIndex(2);//Index starts from 0. so, 0 = Jr.High 1 = HighSchool 2 = College
      

      按值选择:

      SelectAnEducation.SelectByValue("College");//There are 3 values - Jr.High, HighSchool, College
      

      【讨论】:

        【解决方案5】:

        如果您只是从下拉框中寻找任何选择,我还发现“按索引选择”方法非常有用。

        if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
        {
            new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
            WaitForAjax();
            Thread.Sleep(3000);
        }
        else
        {
             Console.WriteLine("Your comment here);
        }
        

        【讨论】:

          【解决方案6】:

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

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

          更多信息here

          【讨论】:

          • 有一个错误。 var selectElement = new SelectElement(education); 应该是:var selectElement = new SelectElement(element);
          • 仅供参考:要使用选择元素,您需要包含 Selenium Webdriver Support 包,它是与 Selenium WebDriver 不同的 NuGet 包。包括命名空间 OpenQA.Selenium.Support.UI.
          • 我使用的是 firefox 驱动程序,selenium 版本 2.53.1 和支持库 2.53,SelectByText 似乎不起作用。我能够看到所有选项。即使我迭代选项并设置正确的值,值也没有设置..任何帮助都会很棒
          • 您尝试了其他驱动程序还是只尝试了 Firefox?此外,该包的技术名称目前是 Selenium.Support。
          • 这对我来说效果很好,还必须添加 Selenium.Support NuGet。
          【解决方案7】:

          通过文本选择选项;

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

          通过值选择选项:

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

          【讨论】:

            【解决方案8】:

            您只需要传递值并输入密钥:

            driver.FindElement(By.Name("education")).SendKeys("Jr.High"+Keys.Enter);
            

            【讨论】:

            • 如果下拉菜单包含多个具有相似文本的选项,则可能会失败。
            【解决方案9】:

            这就是我的工作方式(通过 ID 选择控件并通过文本选择选项):

            protected void clickOptionInList(string listControlId, string optionText)
            {
                 driver.FindElement(By.XPath("//select[@id='"+ listControlId + "']/option[contains(.,'"+ optionText +"')]")).Click();
            }
            

            使用:

            clickOptionInList("ctl00_ContentPlaceHolder_lbxAllRoles", "Tester");
            

            【讨论】:

              【解决方案10】:

              其他方式可能是这个:

              driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();
              

              您可以更改 option[x] 中的索引,将 x 更改为您要选择的元素的数量。

              我不知道这是否是最好的方法,但我希望对你有所帮助。

              【讨论】:

              • 我不确定这是否一直有效。有人这样做了,但没有用,我最终不得不将代码更改为 Matthew Lock 建议的代码
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-10-08
              • 2023-04-11
              • 1970-01-01
              • 2011-07-25
              相关资源
              最近更新 更多