简体   繁体   中英

Selenium/Java: get index/position of currently selected option in a dropdown menu

How do get the index of the currently selected option in a dropdown menu in Selenium? Getting the text label for it is easy

String searchString = select.getFirstSelectedOption().getText();

It is also easy to select the n-th element

select.selectByIndex(25);

But I want to know that the currently selected item's index is 25. When I know that I want to log the value and then select next by index.

I have used the below html code snippet of dropdown:-

<select name="Students">
<option value="student1">student1</option>
<option value="student2">student2</option>
<option value="student3">student3</option>
<option value="student4">student4</option>
</select>

Below is the code for selecting from the dropdown and then getting the index of the option selected:-

    Select sel = new Select(driver.findElement(By.xpath("//select[@name='Students']")));

    sel.selectByVisibleText("student4");

    List<WebElement> list = sel.getOptions();

    for(int i=0;i<list.size();i++){
        if(list.get(i).getText().equals(sel.getFirstSelectedOption().getText())){
            System.out.println("The index of the selected option is: "+i);
            break;
            }
    }

Note:- Output will be "3", as the index starts from "0".

在我们的 Selenium 测试中,使用了一个更简洁的片段:

int index = select.getOptions().indexOf(select.getFirstSelectedOption();

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