简体   繁体   中英

How to select the drop down value in selenium?

I am not able to select the value in drop down in above mentioned code,

 public class Dropdown {

     public static void main(String[] args) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
          System.setProperty("webdriver.chrome.driver", "I:/shopclues/demoqa/drivers/chromedriver.exe");
          ChromeDriver driver= new ChromeDriver();
          driver.get("http://demoqa.com/");
          driver.manage().window().maximize();
          driver.findElementByLinkText("Registration").click();
          driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
          WebElement country = driver.findElementByXPath("//select[@id='dropdown_7']");
          Select dropdown = new Select(country);
          List<WebElement> options = dropdown.getOptions();
          for (WebElement option1 : options) 
          {
              System.out.println(option1.getText());
              if(option1.getText().startsWith("india"))
              {
                  option1.click();
                  break;
              }

          }
     }

 }

Thanks

Based on gihan's answer here , you can select via the following:

dropdown .selectByVisibleText("India"); dropdown.selectByIndex(0); dropdown.selectByValue("India");

For your purposes, the first option should work fine.

Use the following way to select a dropdown -

    WebElement country = driver.findElement(By.id("dropdown_7"));
    Select dropdown = new Select(country);

    dropdown.selectByVisibleText("india");  // pass the text which is visible on site

    //or
    dropdown.selectByIndex(1); // pass the index of dropdown value you want to select

    //or
    dropdown.selectByValue("your_value");

Or change your code

WebElement country = driver.findElementByXPath("//select[@id='dropdown_7']");

to

WebElement country = driver.findElement(By.id("dropdown_7"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM