Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...