Single Post

Header

Sunday, November 1, 2015

How to get List Elements and Select a Value from a DropDown List - Selenium WebDriver

How to Select a value from a DropDown List using Selenium - WebDriver

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;
import org.openqa.selenium.support.ui.Select;
public class MySpiceJet {

   
    public static void main(String[] args) throws Exception
    {
        WebDriver wd=new FirefoxDriver();
        wd.get("http://www.spicejet.com/");
        Thread.sleep(10000);
       
        WebElement from1=wd.findElement(By.id("from1Select"));
        // Get the list from the drop down list Selenium WebDriver
        List<WebElement> list1=from1.findElements(By.tagName("option"));
        for(WebElement i:list1)
        {
            System.out.println(i.getText());
            //Reporter.log(i.getText());
        }
            // Select a value from the drop down list Selenium WebDriver
            Select select=new Select(wd.findElement(By.id("from1Select")));
            select.selectByVisibleText("Tirupati");  

        wd.close();
    }

}

5 comments:

  1. is not working
    Select select=new Select(wd.findElement(By.id("from1Select")));
    select.selectByVisibleText("Tirupati");

    only the below is working
    WebElement from1=driver.findElement(By.name("filterType"));
    List options = from1.findElements(By.tagName("option"));
    for (WebElement option : options) {
    if ("Source ID".equalsIgnoreCase(option.getText())){
    option.click();
    }
    }

    ReplyDelete
  2. Hi Sathish,

    It should work, did you import the below package ?

    import org.openqa.selenium.support.ui.Select;

    ReplyDelete
  3. hello sir,

    could you please add how to print for the selected value - drop down option

    Note: please print for above options, if i select "tirupati" from the option (dropdown), how do i print that?

    Thanks in advance

    Srinivas

    ReplyDelete
  4. Hi Srinivas,
    Sorry for the deply in response, to print the selected value at the drop down list, we need to write code like below
    select.selectByVisibleText("Tirupati"); // after this
    System.out.println("The selected value is"+select.getFirstSelectedOption().getText());

    We get the o/p:
    Tirupati

    ReplyDelete
  5. how to validate the default value which is highlighted/Selected from bootstrap drop down

    ReplyDelete