Select each option in a drop down using Selenium WebDriver C#

后端 未结 5 1832
深忆病人
深忆病人 2021-02-19 00:06

I\'m not able to select options in a drop down list. I think I need to have .Select or SelectElement, but there is no such option.

Sample code:

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 00:52

    Here is an example to better illustrate how to get all the items in a drop down list and to select an item from the drop down list.

    A sample Html code for drop down list

    
    

    Code below gets all the items from the drop down list above and selects item 'Coffee'.Logic of the code is as follows

    Step 1. Create an interface of the web element tag Step 2. Create an IList with all the child elements of web element tag Step 3. Select the Drop List item "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 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();
            }
        }
    }
    

提交回复
热议问题