Arsen Zahray
Arsen Zahray

Reputation: 25297

How to use select list in selenium?

I'm trying to select an element from a select list in selenium using java with WebDriver - based syntax.

I've got the select list by

    elements = driver.findElements(By.xpath("//form[@action='inquiry/']/p/select[@name='myselect']"));
    if (elements.size() == 0) {
        return false;
    }
    if (guests != null) {
        //what do I do here?
    }

How do I do that?

Upvotes: 11

Views: 33422

Answers (4)

Praveen
Praveen

Reputation: 387

Try to do it like this :

//method to select an element from the dropdown

public void selectDropDown(String Value) {

    webElement findDropDown=driver.findElements(By.id="SelectDropDowm");
    wait.until(ExpectedConditions.visibilityOf(findDropDown));
    super.highlightElement(findDropDown);
    new Select(findDropDown).selectByVisibleText(Value);
}

//method to highlight the element

public void highlightElement(WebElement element) {

    for (int i = 0; i < 2; i++) {

        JavascriptExecutor js = (JavascriptExecutor) this.getDriver();
        js.executeScript(
                "arguments[0].setAttribute('style', arguments[1]);",
                element, "color: yellow; border: 3px solid yellow;");
        js.executeScript(
                "arguments[0].setAttribute('style', arguments[1]);",
                element, "");

    }

}

Upvotes: 0

Pavel Janicek
Pavel Janicek

Reputation: 14748

A little side note which applies to Java:

In my case, when I was writing the test according the example of @nilesh, I got a strange error, that the constructor is invalid. My import was:

import org.openqa.jetty.html.Select;

If you happen to have similar errors, you have to correct that import to this:

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

If you use this second import, everything will work.

Upvotes: 7

user591593
user591593

Reputation:

element = driver.findElements(By.xpath("//form[@action='inquiry/']/p/select[@name='myselect']/option[*** your criteria ***]"));
if (element != null) {
    element.click();
}

find the option, and then click it

Upvotes: 1

nilesh
nilesh

Reputation: 14287

WebElement select = driver.findElement(By.name("myselect"));
Select dropDown = new Select(select);           
String selected = dropDown.getFirstSelectedOption().getText();
if(selected.equals(valueToSelect)){
    //already selected; 
    //do stuff
}
List<WebElement> Options = dropDown.getOptions();
for(WebElement option:Options){
    if(option.getText().equals(valueToSelect)) {
      option.click(); //select option here;       
    }               
}

If this is slower, then consider something like

dropDown.selectByValue(value);
or

dropDown.selectByVisibleText(text);

Upvotes: 22

Related Questions