Home > Net >  Selenium Access options for input drop-down list
Selenium Access options for input drop-down list

Time:06-16

I have an input control that acts as a read-only drop-down list (Svelte is framework behind it). How do I get a list of the drop-down options using Selenium and Java please? I have tried the select option:

Select allOptions = new Select(webDriver.getWebDriver().findElement(By.xpath(xpath)));

I got exceptions saying that you cannot select on an input. Because the control is read-only you can't type into it to enter values.

<input readonly="true" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" tabindex="0" type="text" aria-autocomplete="list" id="select-instances" placeholder="Select an instance"  style="">

I have researched answers here, for example this one. You don't get list tags from Svelte. Any suggestions or help would be greatly appreciated.

CodePudding user response:

If Possible can you share pic of html code of the dropdown element

Select allOptions = new 
Select(webDriver.getWebDriver().findElement(By.xpath(xpath)));
List<WebElement> elements = allOptions.getOptions();
List<String> options = new LinkedList<String();
for(WebElement el: elements)
{
    options.Add(el.getText());
}

CodePudding user response:

  1. Open DevTools -> Sources

  2. Click on the input -> Press F8 to stop JS execution in the browser

  3. Inspect dropdown option -> Write down the xpath

    public List<string> GetOptionsText(IWebDriver driver)
    {
        string parentInputXpath = "inputXpath";
        string optionXpath = "optionXpath";
        List<string> optionsText = new List<string>();
    
        driver.FindElement(By.XPath(parentInputXpath)).Click();
        options = driver.FindElement(By.XPath(parentInputXpath)).FindElements(By.XPath(optionXpath)).ToList();
    
        if (options.Count == 0)
            throw new NoSuchElementException("Dropdown options not found");
    
        foreach (var option in options)
        {
            optionsText.Add(option.Text);
        }
        return optionsText;
    }
    

P.S: It would be also good to add implicit/explicit waits here.

  • Related