How do I iterate in drop-down using Selenium Webdriver?

I have a drop-down like B008124/001, B008124/002, B008124/003, B008124/004.

Here I have to select B008124/001 and perform some option like approve. Then I have to select B008124/002 and perform approve the action, and so on.

But the point here is: the mentioned 4 series will not always be the same; it depends on the scenarios and it may vary up to 6, or it maybe 1-2.

enter image description hereenter image description here

  • 1
    Hi Yukesh, for us is better to get the code instead of screenshot.Then we can modify the code. Because in my case I cannot enlarge screenshot... – Daniel Boehm Nov 11 '19 at 11:21
  • 1
    Also when people say "screenshot" they don't normally mean a literal photograph of your monitor... – jonrsharpe Nov 11 '19 at 11:33

The solution as you said would be iterating the dropdown with a loop. Since your question was not clear on; is there multiple dropdown or based on previous scenario the count of options are changed I will assume the later one is the question and my answer will be based on that.

What you can do is:

  • Try to find every element exists in the dropdown
  • Exclude <option>- Select -</option>
  • Select each element and continue accordingly.

To achieve above you need two things:

  • Outer for loop for each element in dropdown.
  • Switch-case or if-else for the inner code of loop.

Here is an example code written in Groovy which you might easily adapt the language you use:

def iterationForAllElements() {
    List<WebElement> options = webDriver.findElements("selector for option elements")  // Get all available option elements into the WebElement list.
    options.each {option ->                     // This is the loop for each element.
       if(option.getAttribute("value") != 0) {  //Here you exclude option 0 since it's not really an option.

           switch(option.getAttribute("value")) // I assumed for each selection there's different corresponding code should be working. 
              case 1:                           //Otherwise you can use something else rather than switch case.
                 .....          //Here the code will be executed by the value **attribute** of option.
              case 2:

You also might wanna check if there's any element in the list beforehand to avoid exceptions which might cause false negative results.

| improve this answer | |
  • @yukesh-raj the code above works for you? – TuRQuaS3 Nov 18 '19 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.