How to select elements from drop-down box

Selecting option/options from drop-down list is a similar operation that we perform earlier for selecting any other type of element on a webpage. You can locate dropdown box by ID, Name, CSS & Xpath etc. 

In order to select a drop-down value with selenium web-driver, you need to create a Select object of class Select by importing ‘import org.openqa.selenium.support.ui.Select' package

Let’s consider the following drop down element for our example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<html>
<head>
<title>Select Example</title>
</head>
<body>
<select id="mySelect">
<option value="option1">Pune</option>
<option value="option2">Mumbai</option>
<option value="option3">Nagpur</option>
<option value="option4">Thane</option>
<option value="option5">Kolhapur</option>
<option value="option6">Nasik</option>
</select>
</select>
</body>
</html>

**Note:- Copy the above code and paste in notepad and save the file as "DropDownDemo.html" in your C drive. This step will require if you would like to execute following code on your PC.

Lets try to understand the selenium code to select options from above drop-down

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import org.openqa.selenium.support.ui.Select;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Demo {

 public static void main(String[] args){

  System.setProperty("webdriver.gecko.driver", "./MyProject/driver/geckodriver.exe");
  WebDriver driver = new FirefoxDriver();
  driver.get("file:///C:/DropDownDemo.html");

  // We need to create a new Select Object of class Select.
  // Select class helps to perform multiple operations on DropDown
  WebElement element = driver.findElement(By.id("mySelect"));
  Select DropDownDemo = new Select(element);

  // Elements can be selected by one of following three methods
  // 01_Select by Index
  DropDownDemo.selectByIndex(1);

  // 02_Select by visible text
  DropDownDemo.selectByVisibleText("Nasik");

  // 03_Select by value
  DropDownDemo.selectByValue("option5");

  // To get and print all options from drop-down
  List<WebElement> options = DropDownDemo.getOptions();

  for (WebElement option : options) {
   System.out.println(option.getText());
  }

  // Select all elements from multiselect dropdownlist
  WebElement element1 = driver.findElement(By.id("cars"));
  Select MultiSelectDropDownDemo = new Select(element1);
  List<WebElement> options_List = MultiSelectDropDownDemo.getOptions();

  for (WebElement opt : options_List) {
   opt.click();
  }

  // To deselect all options
  MultiSelectDropDownDemo.deselectAll();
 }
}



<-- Previous || Next -->

No comments:

Post a Comment