How to get all options in a drop-down list by Selenium WebDriver using C#?

后端 未结 11 844
闹比i
闹比i 2020-12-30 02:30

I\'m new to both C# and Selenium WebDriver.

I know how to select/click on an option in a drop-down list, but I\'ve a problem before that. Since the drop-down list i

相关标签:
11条回答
  • 2020-12-30 02:39

    Use IList<IWebElement> instead of List<IWebElement>.

    For instance:

    IList<IWebElement> options = elem.FindElements(By.TagName("option"));
    foreach (IWebElement option in options)
    {
        Console.WriteLine(option.Text);
    }
    
    0 讨论(0)
  • 2020-12-30 02:48

    To get all options in a drop-down list by Selenium WebDriver C#:

    SelectElement TimeZoneSelect = new SelectElement(driver.FindElement(By.Name("time_zone")));
    IList<IWebElement> ElementCount = TimeZoneSelect.Options;
    int ItemSize = ElementCount.Count;
    
    for (int i = 0; i < ItemSize; i++)
    {
        String ItemValue = ElementCount.ElementAt(i).Text;
        Console.WriteLine(ItemValue);
    }
    
    0 讨论(0)
  • 2020-12-30 02:50

    Here is code in Java to get all options in dropdown list.

    WebElement sel = myD.findElement(By.name("dropdown_name"));
    List<WebElement> lists = sel.findElements(By.tagName("option"));
        for(WebElement element: lists)  
        {
            String var2 = tdElement.getText();
            System.out.println(var2);
        }
    

    Hope it may helpful to someone.

    0 讨论(0)
  • 2020-12-30 02:50

    It seems to be a cast exception. Can you try converting your result to a list i.e. elem.findElements(xx).toList ?

    0 讨论(0)
  • 2020-12-30 02:52
    To get all the dropdown values you can use List.
    
    List<string> lstDropDownValues = new List<string>();
    int iValuescount = driver.FindElement(By.Xpath("\html\....\select\option"))
    
    for(int ivalue = 1;ivalue<=iValuescount;ivalue++)
     {
      string strValue = driver.FindElement(By.Xpath("\html\....\select\option["+ ivalue +"]"));
      lstDropDownValues.Add(strValue); 
     }
    
    0 讨论(0)
  • 2020-12-30 02:53

    Make sure you reference the WebDriver.Support.dll assembly to gain access to the OpenQA.Selenium.Support.UI.SelectElement dropdown helper class. See this thread for additional details.

    Edit: In this screenshot, you can see that I can get the options just fine. Is IE opening up when you create a new InternetExplorerDriver? Screenshot

    0 讨论(0)
提交回复
热议问题