Jai
Jai

Reputation: 11

How to click on a Dropdown menu through Selenium

Actions a= new Actions(driver);
WebElement mainmenu=driver.findElement(By.xpath(".//*[@id='yui-gen2']/a"));
a.moveToElement(mainmenu).build().perform();
WebElement Sub = driver.findElement(By.xpath(".//*[@id='helpAbout']"));    
a.moveToElement(Sub).build().perform();
Sub.click();

Code couldn't click on submenu, it just stops at 3rd line.

screenshot

Upvotes: 0

Views: 17202

Answers (4)

Bayram Binbir
Bayram Binbir

Reputation: 2217

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

WebElement selectElement; 
selectElement= driver.findElement(By.id("yourElementId"));
  or 
selectElement driver.findElement(By.xpath("yourElementXpath"));

Select selectObject = new Select(selectElement);

The Select object will now give you a series of commands that allow you to interact with a element. First of all, there are different ways of selecting an option from the element.

<select>
<option value=value1>Bread</option>
<option value=value2 selected>Milk</option>
<option value=value3>Cheese</option>
</select>

// Select an <option> based upon the <select> element's internal index
selectObject.selectByIndex(1);

// Select an <option> based upon its value attribute
selectObject.selectByValue("value1");

// Select an <option> based upon its text. Example: Bread
selectObject.selectByVisibleText("Bread");

Upvotes: 0

Ishita Shah
Ishita Shah

Reputation: 4035

Your code is 90% correct, just replace following code:

a.moveToElement(Sub).click().perform(); 

build() method works for hover on element,and after hover on it we have to click element.

Upvotes: 1

Charles Nough
Charles Nough

Reputation: 365

With selenium you should be able to just do the following:

Select variableName = new Select(DropDownElementLocator);
variableName.selectByVisibleText("Whatever");
// or
variableName.selectByIndex(1);

Upvotes: 3

undetected Selenium
undetected Selenium

Reputation: 193108

Once you Mouse Hover over the element identified as By.xpath(".//*[@id='yui-gen2']/a") and therefafter invoke moveToElement(mainmenu), build(), perform(), at this stage the element identified as By.xpath(".//*[@id='helpAbout']") is visible and interactable. So you need to invoke click() directly as follows :

Actions a= new Actions(driver);
WebElement mainmenu=driver.findElement(By.xpath(".//*[@id='yui-gen2']/a"));
a.moveToElement(mainmenu).build().perform();
WebElement Sub = driver.findElement(By.xpath(".//*[@id='helpAbout']"));    
Sub.click();

Upvotes: 0

Related Questions