Iterating in drop down through selenium web driver



  • 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



  • 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:
                     .....
                  default:
                     .....
           }
        }
    }
    

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


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2