How to get all options in a drop-down list by Sele

2020-02-25 07:38发布

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 is dynamically generated, I have to get all options/values from the list before running each case.

Is there anyone kindly tell me how to get all values/options from a drop-down list. I'm using IE and I didn't find any class which supports method to get values/options in Selenium.IE namespace for C#.

My example: A list contains several time zones:

<TD>
  <select name = "time_zone">
    <option value "-09:00"><script>timezone.Alaska</script></option>
    <option value "+00:00"><script>timezone.England</script></option>
    <option value "+02:00"><script>timezone.Greece</script></option>
    <option value "+05:30"><script>timezone.India</script></option>
  </select>
<TD>

This is a drop-down list in an IE page and how to get the dynamically generated time zone list?

My code:

IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
List<IWebElement> options = elem.FindElements(By.TagName("option"));

C# just pops an Error: Cannot implicitly covert type 'OpenQA.Selenium.IWebElement' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?).

thanks.

11条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-25 08:09
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); 
 }
查看更多
神经病院院长
3楼-- · 2020-02-25 08:09
 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }
查看更多
家丑人穷心不美
4楼-- · 2020-02-25 08:12
WebElement drop_down =driver.findElement(By.id("Category"));
Select se = new Select(drop_down);
for(int i=0 ;i<se.getOptions().size(); i++)
System.out.println(se.getOptions().get(i).getAttribute("value"));
查看更多
啃猪蹄的小仙女
5楼-- · 2020-02-25 08:17

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

查看更多
聊天终结者
6楼-- · 2020-02-25 08:19
Select select = new Select(driver.findElement(By.id("searchDropdownBox")));

select.getOptions();//will get all options as List<WebElement>
查看更多
登录 后发表回答