Saturday, February 27, 2016

WebDriver - Select Item From Drop-down

WebDriver - Select Item From Drop-down


In the below examples we are using drop-down from Amazon.in and are trying to select 3rd item ("Baby") from the drop-down.



Example 1 - Select an Item from Drop-down
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;

namespace Project_1
{
    [TestClass]
    public class UnitTest1
    {
       [TestMethod]
       public void TestMethod1()
       {
         IWebDriver driver = new FirefoxDriver();
         driver.Navigate().GoToUrl("https://amazon.in");
         var select = driver.FindElement(By.Id("searchDropdownBox"));
         var babyOption = select.FindElements(By.TagName("Option"))[2];
         babyOption.Click();
       }
    }
}

In above code, we are using "TagName" to find an element or rather array of elements using FindElements.

As we have to select "Baby" from the drop-down list and "Baby" being the 3rd item in the list, we have used the index 2 above (as it is 0 indexed). In the last line we are using the click method to select an item.

Example 2 - Select an Item from Drop-down
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;

namespace Project_1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
          IWebDriver driver = new FirefoxDriver();
          driver.Navigate().GoToUrl("https://amazon.in");
          var select = driver.FindElement(By.Id("searchDropdownBox"));
          var selectElement = new SelectElement(select);
          selectElement.SelectByText("Baby");
        }
    }
}

In above code, we are wrapping WebElement into Select Object and using method like SelectByText to find an item in the drop-down. For this to work, make sure you have added "WebDriver.Support" DLL along with "WebDriver" DLL.