Home > database >  How to select an option from a dropdown using Selenium
How to select an option from a dropdown using Selenium

Time:10-06

I have this dropdown:

<select  data-bind="
    attr: {
        name: inputName,
        id: uid,
        disabled: disabled,
        'aria-describedby': noticeId
    },
    hasFocus: focused,
    optgroup: options,
    value: value,
    optionsCaption: caption,
    optionsValue: 'value',
    optionsText: 'label'" name="product[business_line]" id="N2JWY3F" aria-describedby="notice-N2JWY3F"><option value=""> </option><option data-title="PU - 21" value="425">PU - 21</option><option data-title="PU - 35" value="430">PU - 35</option></select>

The XPath is:

//*[@id="N2JWY3F"]

It has 2 options available: PU - 21 and PU - 35. I want to select the option: PU - 21.

I did this:

First, click on that dropdown:

driver.findElement(By.xpath("//*[@id=\"N2JWY3F\"]")).click();

How can I specify the option that I want? I tried different things and not one worked.

CodePudding user response:

Try:

driver.findElement(By.xpath("//*[@id=\"N2JWY3F\"]")).Select(select_by_value('425'));

CodePudding user response:

I'm guessing the drop-down isn't being clicked properly; can you check if "/*[@id="N2JWY3F"]" has only one match, and if so, maybe you can experiment with some other attributes:

driver.findElement(By.id("N2JWY3F"));
OR
driver.findElement(By.name("product[business_line]"));
OR
driver.findElement(By.className("admin__control-select"));

If updating the locator does not work, make sure the page is loaded and the drop-down menu is enabled before clicking. You can either wait or make sure the drop-down menu is visible on the page.

  • Related