开发者

Selenium: Get current value from drop-down menu

I'm trying to find a simple Selenium call to grab the current option from a select drop-down list. I'm aware there are calls which grab all the values in a list but I wish to know which option is currently selected. Apologies if this is trivial b开发者_如何学编程ut google and Selenium IDE didn't help me. Thanks.


You should be able to use the getSelected* commands to return the ID, index, or label of the selected item. Below is quoted from the Selenium Reference:


storeSelectedId ( selectLocator, variableName )
Gets option element ID for selected option in the specified select element.

Arguments:

  • selectLocator - an element locator identifying a drop-down menu
  • variableName - the name of a variable in which the result is to be stored.

Returns: the selected option ID in the specified select drop-down


storeSelectedIndex ( selectLocator, variableName )
Gets option index (option number, starting at 0) for selected option in the specified select element.

Arguments:

  • selectLocator - an element locator identifying a drop-down menu
  • variableName - the name of a variable in which the result is to be stored.

Returns: the selected option index in the specified select drop-down


storeSelectedLabel ( selectLocator, variableName )
Gets option label (visible text) for selected option in the specified select element.

Arguments:

  • selectLocator - an element locator identifying a drop-down menu
  • variableName - the name of a variable in which the result is to be stored.

Returns: the selected option label in the specified select drop-down


I would use storeSelectedValue or getSelectedValue

JUNIT

String value = selenium.getSelectedValue(selectLocator)


Selenium Action

storeSelectedValue ( selectLocator, variableName ) 


there is a link to practice such things:

"https://letskodeit.teachable.com/p/practice"

there's a "Select Class Example"

1.in this test first it clicks on "Honda" in the dropdown menu 2. then extracts the select-tag as parent of the option-tag "Honda" 3. then converts it to Select object 4. then i uses the getFirstSelectedOption() to compare it with the expected value "Honda.

    @Test
    public void selectTagDemo() {
        WebElement hondaElement = webDriver.findElement(By.xpath("//option[@value=\"honda\"]"));
        hondaElement.click();

        WebElement selectCarWebElement = hondaElement.findElement(By.xpath("//parent::select"));
        Select selectCar = new Select(selectCarWebElement);
        Assert.assertEquals(selectCar.getFirstSelectedOption().getText(), "Honda");
    }

if you need the whole Test class comment below

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜