Paso
Paso

Reputation: 1

button dropdown automation in selenium

How do I automate selection of a dropdown value in the following sample code:

<div class="dropdown">
  <button id="dropdown-button-1" class="dropdown-toggle btn btn-default-alt" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Button Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdown-button-1">
    <li role="presentation">
      <a href="http://www.google.com" role="menuitem">Google</a>
    </li>
    <li class="divider mvn"></li>
    <li role="presentation">
      <a href="http://www.yahoo.com" role="menuitem">Yahoo</a>
    </li>
    <li class="divider mvn"></li>
    </li><li role="presentation">
      <a href="http://www.aol.com" role="menuitem">Aol</a>
    </li>
  </ul>
</div>

Select clearly doesn't work as this is not a regular drop down menu, selenium detects this element as a button.

Upvotes: 0

Views: 5378

Answers (2)

sagarwadhwa1
sagarwadhwa1

Reputation: 942

How about using driver clicks and waits ? That's how I went about it.

WebElement button = driver.findElement(By.id("dropdown-button-1"));
button.click();
WebElement we = new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@aria-labelledby='dropdown-button-1']")));
By pathOfSelection = By.xpath("./li[@role='presentation']/a[text()='Google']"); // if you need to select options other than Google, you can change the text to any of the options.
WebElement option = null;
try {
   option = we.findElement(pathOfSelection);
} catch(NoSuchElementException e){
   System.out.println("No such option. " + e.getMessage);
   throw e;
}
option.click();

You can verify if the right element has been selected by doing a getText on the button.

if(!"Google".equals(button.getText())) {
    throw new Exception("Incorrect option selected");
}

Upvotes: 2

Shahid Algur
Shahid Algur

Reputation: 21

Try using Actions. For more reference kindly visit : https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html

Here is sample code :

Actions actions = new Actions(driver);
WebElement abc = driver.findElement(By.xpath("xpath of drop down"));
actions.moveToElement(abc);
actions.moveToElement(driver.findElement(By.id("desired option"))).click().perform();

Note : U can also use xpath in move to element.

Upvotes: 1

Related Questions