Select Class in Selenium


Select Class in Selenium



Selenium supports “Select” class, which provides useful methods for interacting with select options. User can perform operations on a select drop-down and also de-select operation using the below methods.

Note: Add using OpenQA.Selenium.Support.UI; in namespace Section

SelectByIndex 
Syntax: select.selectByIndex(Index);
Purpose:  To Select the option based on the index given by the user.
There is an attribute called "values" which will have the index values.

SelectByValue
Syntax: select.selectByValue(Value);
Purpose:  To Select the options that have a value matching with the given argument by the user.

SelectByText
Syntax: select.selectByText(Text);
Purpose: To Select all options that display text matching the given argument.
It will not look for any index or value, it will try to match the VisibleText (which will display in dropdown)

deselectByIndex  
Syntax: select.deselectByIndex(Index);
Purpose: To Deselect the option at the given index. The user has to provide the value of index.

 deselectByValue  
Syntax: select.deselectByValue(Value);
Purpose: To Deselect all options that have a value matching the given argument.

 deselectByVisibleText  
Syntax: select.deselectByVisibleText(Text);
Purpose: To Deselect all options that display text matching the given argument.

deselectAll
Syntax: select.deselectAll();
Purpose: To Clear all selected entries.
This works only when the SELECT supports multiple selections.
It throws NotImplemented eError if the "SELECT" does not support multiple selections. In select it mandatory to have an attribute multiple="multiple"


Example:To select (day,month,year) in birthday field in "WWW.FACEBOOK.COM"


IWebDriver chrome = new ChromeDriver(); //Open chrome browser chrome.Navigate().GoToUrl("https://facebook.com"); //open facebook website
 //wait until elements are available 
chrome.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

//To select date AND SELECTBYVALUE
 var day = chrome.FindElement(By.Id("day"));
 var select_day = new SelectElement(day); 
 select_day.SelectByValue("2"); 


 //To select month by SELECTBYTEXT
 var month = chrome.FindElement(By.Id("month")); 
 var select_month = new SelectElement(month); 
 select_month.SelectByText("Oct");


 //To select year by SELECTBYINDEX
 var year = chrome.FindElement(By.Id("year"));
 var select_year = new SelectElement(year); 
 select_year.SelectByIndex(5);


In our next tutorial let us learn about cookies!


No comments:

Post a Comment