7

I have Select Dropdown list with this:

xpath //*[@id="ddlTablePay"] 

I need to count the number of options in this drop-down. Thank You

iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
Jaydev
  • 133
  • 2
  • 3
  • 10

6 Answers6

11

Use .getOptions() method and store them in a list .Then find its size.

Select se = new Select(driver.findElement(By.id("select drop down locator")));

List<WebElement> l = se.getOptions();
l.size();

-Ajay

Mark Rowlands
  • 5,357
  • 2
  • 29
  • 41
Ajay
  • 395
  • 1
  • 4
  • 11
3
String[] options = driver.findElement(By.id("dropdown")).getText().split("\n");
options.length;
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
IVI4K LI
  • 31
  • 1
2

Use .getXpathCount() method

int numOptions = selenium.getXpathCount("//*[@id='ddlTablePay']/option").intValue();
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
Meena T
  • 21
  • 3
0
optionItems = Select(driver.find_element_by_xpath("//select[@id='ddlTablePay']"))
print "Total Elements " + str(len(optionItems.options))
Sharanabasu Angadi
  • 4,304
  • 8
  • 43
  • 67
0

//To count the number of options

Select dropDown = new Select(driver.findElement(By.id("ddlTablePay")));
List<WebElement> elementCount = dropDown.getOptions();
System.out.println("Number of items: " + elementCount.size());

//To get and print all the Options

Select dropDown = new Select(driver.findElement(By.id("ddlTablePay")));
        List <WebElement> elementCount = dropDown.getOptions();
        int itemSize = elementCount.size();
        for(int i = 0; i < itemSize ; i++){
            String optionsValue = elementCount.get(i).getText();
            System.out.println(optionsValue);
        }
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
  • I have used ID instead of xpath though xpath also definitely works. ID is more preferable than xpath if any control/element has ID. – Ripon Al Wasim Sep 02 '16 at 12:11
0

Pass the xpath of the dropdown whose count you want:

static int getDropdownListCount(String xpath) {
        
    WebElement element = driver.findElement(By.xpath(xpath));
    Select select = new Select(element);
    List<WebElement> elements = select.getOptions();
    return elements.size();
}

It'll return count of total number of options under that dropdown.

Aawara
  • 301
  • 3
  • 18