How to work SELECT Methods with Dropdowns in Selenium Webdriver using java.

Select class provides useful methods for interacting with select options. User can do operations on a select dropdown and also de-select operation using the below methods. User can also get the text of the values in the dropdown.
HTML Code:
<html>
<head>
<title>Selenium WebDriver- Drop Down Interaction</title>
</head>
<body>
<select id="language">
<option value="java">Java</option>
<option value="c">C</option>
<option value="perl">Perl</option>
<option value="php">PHP</option>
<option value="python">Python</option>
<option value="javascript">JavaScript</option>
</select>
</body>
</html>


Method Name: selectByVisibleText
Syntax: selectByVisibleText(String text)
Description: Select all options that display text matching the argument.. It will not look for any index or value, it will try to match the VisibleText (which will display in dropdown)
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
  dropdown.selectByVisibleText("Python");

 
Method Name: selectByValue
Syntax: selectByValue(String value)
Description: Select all options that have a value matching the argument.
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
 dropdown.selectByValue("php"); 


Method Name: selectByIndex
Syntax: selectByIndex(int index)
Description: Select the option at the given index.
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
 dropdown.selectByIndex(3);


Method Name: deselectByVisibleText 
Syntax: deselectByVisibleText(String text)
Description: Deselect all options that display text matching the argument.
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
  dropdown.deselectByVisibleText("Python");


Method Name:  deselectByValue 
Syntax: deselectByValue(String text)
Description: Deselect all options that have a value matching the argument.
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
 dropdown.deselectByValue("php");


Method Name: deselectByIndex 
Syntax: deselectByIndex(int index)
Description: Deselect the option at the given index.
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
 dropdown.deselectByIndex(3);


Method Name: deselectAll
Syntax: deselectAll()
Description: To Clear all selected entries.
Example:
 Select dropdown = new Select(driver.findElement(By.id("language")));
 dropdown.deselectAll();


Method Name: getOptions
Syntax: List<WebElement> getOptions()
Description: Get all options belonging to this select tag
Example:
Select dropdown = new Select(driver.findElement(By.id("language")));
List<WebElement> allOptions = dropdown.getOptions();
for (WebElement webElement : allOptions){
System.out.println(webElement.getText());}


Method Name: getAllSelectedOptions
Syntax: List<WebElement> getAllSelectedOptions()
Description: Return all selected options belonging to this select tag
Example:
Select dropdown = new Select(driver.findElement(By.id("language")));
List<WebElement> allOptions = dropdown.getAllSelectedOptions();
for (WebElement webElement : allOptions){
System.out.println(webElement.getText());}


Method Name: getFirstSelectedOption
Syntax: WebElement getFirstSelectedOption()
Description: Get the first selected option in this select tag (or the currently selected option in a normal select)
Example:
Select dropdown = new Select(driver.findElement(By.id("language")));
WebElement firstOption = dropdown.getFirstSelectedOption();
System.out.println(firstOption.getText());

Method Name: isMultiple
Syntax: boolean isMultiple()
Description:  Whether this select element support selecting multiple options at the same time? This is done by checking the value of the "multiple" attribute
Example:
Select dropdown = new Select(driver.findElement(By.id("language")));
boolean multiple= dropdown.isMultiple();

Detail Example with java code

How to use locators in Selenium Webdriver using java

Selenium WebDriver use locators to find the elements on web page with the help of findElement() and findElements() methods provided by WebDriver and WebElement class.
  • findElement() returns a WebElement object based on a specified search criteria or throw an exception if it does not find any element matching the search criteria.
  • findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list. 
The locators elements of Selenium Webdriver as run as following with java syntax and example.
1. id
2. class name
3. Linktext
4. Partial Linktext
5. Tag Name
6. Name
7. Css
8. xpath

Method: By ID
Syntax: driver.findElement(By.id(<element ID>))
Description: Locates an element using the ID attribute. The most efficient way and preferred way to locate an element on a web page is By ID. ID will be the unique on web page which can be easily identified. IDs are the safest and fastest locator option and should always be the first choice even when there are multiple choices, It is like an Employee Number or Account which will be unique.
Example:
<input type="text"  id="email" name="email" class="inputtext">
<div id="main_menu">Home.</div>

Selenium Webdriver write as:
WebElement loginemail= driver.findElement(By.id("email"));
String menuname= driver.findElement(By.id("main_menu")).getText();

driver.findElement(By.id("email")).sendKeys("abced@gmail.com");

Method: By class name
Syntax: driver.findElement(By.className(<element class>)), driver.findElements(By.className(<element class>))
Description: Locates an element using the Class attribute. There may be multiple elements with the same name. We use findElement() method for single element class name. We use findElements() for  multiple elements with the same name.
Example:
<input type="text"  id="email" name="email" class="inputtext">
<input type="password" id="pass" name="pass" class="inputtext">

or
<input name="register" class="required" type="text"/> 
<div class="mobile">8801911444444.</div>
Selenium Webdriver write as:
List<WebElement> noinputf = table.findElements(By.className("inputtext"));
or
WebElement loginemail= driver.findElement(By.className("required"));

WebElement loginemail= driver.findElement(By.className("mobile")).getText();

Method: By link text
Syntax: driver.findElement(By.linkText(<linktext>))
Description: Locates a link using link text. Make sure, there is only one unique link on the web page. If there are multiple links with the same link text (such as repeated header and footer menu links), in such cases Selenium will perform action on the first matching element with link.
Example:
<a href="http://selenium-release.storage.googleapis.com/2.45/selenium-java-2.45.0.zip">Download</a>
<a href="/projects/">Selenium Projects</a>

Selenium Webdriver write as:
WebElement download = driver.findElement(By.linkText("Downloads"));
driver.findElements(By.linkText("Selenium Projects")).click();


Method: By partial link text
Syntax: driver.findElement(By.partialLinkText(<linktext>))
Description: Locates a link using the link's partial text. It is same as By link text
Example:
<a href="http://selenium-release.storage.googleapis.com/2.45/selenium-java-2.45.0.zip">Download</a>
<a href="/projects/">Selenium Projects</a>

Selenium Webdriver write as:
WebElement download = driver.findElement(By.partialLinkText("Downloads"));
driver.findElements(By.
partialLinkText("Selenium")).click();

Method: By tag name
Syntax: driver.findElement(By.tagName(<htmltagname>))
Description: Locates an element using the HTML tag. It is very easy to handle tables,Select, and check-boxes / drop downs etc  with the help of this method.
Example:
<table style="width:100%" id="data">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table> 


<a href="http://selenium-release.storage.googleapis.com/2.45/selenium-java-2.45.0.zip">Download</a>
<a href="/projects/">Selenium Projects</a> 

Selenium Webdriver write as:
WebElement table = driver.findElement(By.id("data"));
List<WebElement> row = table.findElements(By.tagName("tr"));


List<WebElement> links= driver.findElements(By.tagName("a"));
 
Method: By name
Syntax: driver.findElement(By.name(<element name>))
Description: Locates an element using the Name attribute. Name attribute can't be unique all the times. If there are multiple names, Selenium will always perform action on the first matching element.
Example:
<input type="text"  name="email" class="inputtext">
Selenium Webdriver write as:
WebElement email= driver.findElement(By.name("email"));

Method: By CSS
Syntax: driver.findElement(By.cssSelector(<css selector>))
Description: Locates an element using the CSS selector. The CSS is used as a method to provide style rules for the web pages and we can use for identifying one or more elements in the web page using css.
Example:
WebElement login = driver.findElement(By.cssSelector("input.login"));

Method: By XPath
Syntax: driver.findElement(By.xpath(<xpath>))
Description: Locates an element using XPath query. XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing.
Example:
driver.findElement(By.xpath("html/head/body/table/tr/td"));
 

How to setup and configure selenium webdriver environment with Eclipse?.


Software Requirement
  • JDK
  •  Eclipse
  • Selenium WebDriver Library
  • FireBug and FirePath
Setting up the environment involves the following steps.
  • Download and Install SDK
  • Download and Configure NetBean IDK or  Eclipse with Selenium Webdriver
  • Configure FireBug and FirePath
  • Configure Selenium WebDriver
Download and Install SDK
We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Please follow below step to download and install JDK.

Step 2 : Go to "Downloads" section and select "JDK Download".  
Step 3 : Select "Accept License Agreement" radio button. 
Step 4 : Select the desired installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk. 
Step 5 : Click the downloaded exe file to launch the Installer wizard. Click 'Next' to continue.  
Step 6 : Select the features and click 'Next'.  
Step 7 : The installer is extracted and its progress is shown in the wizard.  
Step 8 : The user can choose the install location and click 'Next'. 
Step 9 : The installer installs the JDK and new files are copied across. 
Step 10 : The Installer installs successfully and displays the same to the user. 
Step 11 : To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error.
 


Configure Selenium WebDriver
Step 1 : Go to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below.


Step 2 : The downloaded file is in Zipped format and one has to unzip





Step 3 : The Unzipped contents would be displayed as shown below.  

Download and Configure Eclipse with Selenium Webdriver

Step 1 : Navigate to the URL: http://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture.   
Step 2 : Click the 'Download' button.  

 Step 3 : The download would be in a Zipped format. Unzip the contents.


 
Step 4 : Locate Eclipse.exe and double click on the file. 
Step 5 : To configure the workspace, select the location where the development has to take place.
Step 6 : The Eclipse window opens as shown below.
Step 7 : Create new java project from File > New > Project > Java Project

Step 8 : Write project name like 'SeleniumWebdriverTest' as shown in bellow given figures.


Step 9 : Right click on project name and select New > Package.


Step 10 : Write package name is 'mypackage' and click on finish button. It will add new package with name 'mypackage' under project name.


Step 11 : Right click on package 'mypackage' and select New > Class and set class name = 'MyClass'


Step 12 : click on Finish button. It will add new class 'MyClass' under package 'mypackage'.


Step 11 :   Add external jar file to java build path and need to add Selenium WebDriver jar files in to java build path. 

  • Right click on project 'SeleniumWebDriverTest' > Select Properties 
  • Select Java build path > Navigate to Libraries tab 
  •  Click on add external JARs button > select all jar files(selenium-2.45.0 + selenium-java-2.45.0-srcs.jar +All jar in libs folder)

Step 12 : Click OK. and project looks like


Step 13 : Write a simple code and run the test script by right clicking test script  > Choose Run As > Choose Java

package mypackage;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class MyClass{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         // Initialize driver      
        WebDriver dr = new FirefoxDriver();  
        //Maximize browser window       
        dr.manage().window().maximize();  
        //Go to URL      
        dr.get("http://www.google.com");  
        //Set  timeout      
        dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
  
        //close firefox browser  
        dr.close();  
    }
    
}
 
 
Step 14: Output will be shown like below
 

Configure FireBug and FirePath
FireBug and FirePath very vital to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins. 
Step 1 : Go to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin.

Step 2 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.


Step 3 : After installing, we can launch the plugin by navigating to "Web Developer" --> "Firebug".


Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/"


Step 5: The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.

 Step 6 : Now launch "Firebug" by navigating to "Tools" --> "Webdeveloper" --> "Firebug". 
Example
Step 1 : First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact.



Step 2 : To fetch the XPath of the object, go to 'firepath' tab and perform the following steps.

  • Click the Spy icon.
  • Select the Control for which we would like to capture the XPath
  • XPath of the selected control would be generated

How to setup and configure selenium webdriver environment with NetBeans?.


Software Requirement
  • JDK
  • NetBean IDE
  • Selenium WebDriver Library
  • FireBug and FirePath
Setting up the environment involves the following steps.
  • Download and Install SDK
  • Download and Configure NetBean IDK or  Eclipse with Selenium Webdriver
  • Install and Configure FireBug and FirePath
  • Configure Selenium WebDriver
Download and Install SDK
We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Please follow below step to download and install JDK.

Step 2 : Go to "Downloads" section and select "JDK Download".  
Step 3 : Select "Accept License Agreement" radio button. 
Step 4 : Select the desired installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk. 
Step 5 : Click the downloaded exe file to launch the Installer wizard. Click 'Next' to continue.  
Step 6 : Select the features and click 'Next'.  
Step 7 : The installer is extracted and its progress is shown in the wizard.  
Step 8 : The user can choose the install location and click 'Next'. 
Step 9 : The installer installs the JDK and new files are copied across. 
Step 10 : The Installer installs successfully and displays the same to the user. 
Step 11 : To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error.
 


Configure Selenium WebDriver
Step 1 : Go to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below.


Step 2 : The downloaded file is in Zipped format and one has to unzip





Step 3 : The Unzipped contents would be displayed as shown below.  

 
 

Download and Configure Netbeans IDE with Selenium Webdriver
Download:
Step 1 : Navigate to the URL: https://netbeans.org/downloads/index.html and download
Step 2 : Click the 'Download' button.  
Installation:
Step 3 : Click the downloaded exe file to launch the Installer wizard. Click 'Next' to continue. 

Step 4 : Click on 'Next'
 

Step 5 : Select license agreement then Click on 'Next'

Step 6 : Select your desired option then Click on 'Next'


Step 7 : Click on 'Next'


Step 8 : Click on 'Next'

Step 9 : Click on 'Next'

Step 10 : Click on 'Install'




Step 11 : Click on 'Finish'
  

Configure NetBeans IDE With Selenium WebDriver
Step 12 : Click on 'Start' --> Write 'Netbeans' on search input field then click on 'Netbeans'

Step 13 : Go to File->New Project->Categories Java and Projects Java Application and click next.

Step 14 : Give the Project Name and Destination where it it will be saved and click finished.

Step 15 : Right Click on project which is shown on the left side of NetBeans and select Properties

Step 16 : Add all jars with in the selenium-2.45.0 folder (selenium-2.45.0 + selenium-java-2.45.0-srcs.jar +All jar in libs folder) 

Step 17 : After adding the all jar this should be shown on the NetBeans.
Step 18 :Now we are ready to write code in NetBeans using Selenium WebDriver.Here we write some code like
package seleniumfirstproject;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Seleniumfirstproject {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         // Initialize driver      
        WebDriver dr = new FirefoxDriver();  
        //Maximize browser window       
        dr.manage().window().maximize();  
        //Go to URL      
        dr.get("http://www.google.com");  
        //Set  timeout      
        dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
  
        //close firefox browser  
        dr.close();  
    }
    
}
 

Step 19 : Right click on source code then click on 'Run File
Step 20 : 'firefox will be opened and show the google page like this


 Configure FireBug and FirePath
FireBug and FirePath very vital to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins. 
Step 1 : Go to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin.

Step 2 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.


Step 3 : After installing, we can launch the plugin by navigating to "Web Developer" --> "Firebug".


Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/"


Step 5: The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.

 Step 6 : Now launch "Firebug" by navigating to "Tools" --> "Webdeveloper" --> "Firebug". 
 Example
Step 1 : First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact.



Step 2 : To fetch the XPath of the object, go to 'firepath' tab and perform the following steps.

  • Click the Spy icon.
  • Select the Control for which we would like to capture the XPath
  • XPath of the selected control would be generated