How to get all options in a drop-down list by Selenium WebDriver using C#?


We can get all options in a drop−down list by Selenium Webdriver in C#. The static drop−down in an html code is identified with a select tag. All the options for a drop−down have the option tag.

To obtain all the options in the form of a list, we shall first identify that element with the help of any of the locators like id, xpath, name, and so on. Then we must create an object of the SelectElement class and apply Options method on it.

Let us investigate the html code of drop−down.

For implementation we shall be using the NUnit framework.

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
namespace NUnitTestProject1{
   public class Tests{
      String u = "https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //launching URL
         d.Navigate()
         .GoToUrl(u);
         //identify dropdown
         IWebElement l = d.FindElement(By.Name("continents"));
         //object of SelectElement
         SelectElement s = new SelectElement(l);
         //Options method to get all options
         IList<IWebElement> els = s.Options;
         //count options
         int e = els.Count;
         for (int j = 0; j < e; j++){
            Console.WriteLine("Option at " + j + " is: " + els.ElementAt(j).Text);
         }
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}

Output

Click on Run All Tests

Click on Open additional output for this result link −

We should get the Test Outcome and Standard Output.

Updated on: 30-Jan-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements