How To Select Random Value From Any Drop down In Selenium Web Driver

Hello Guys,

When you are automating any functionality, you may need to select value from drop down. What should be selected value, generally you want it from user. There might be many scenarios where you just need to select any value from drop down.

For example: Consider User registration where you need to select country , gender and date of birth from drop down and you do not required any special values provided by external sources. You just need to select any values from drop down to proceed further. In this case we should select any value from drop down.

Consider another scenario of running your test scripts in multiple environment where drop down has different values based on environment.  You need to prepare separate data sheet as per environment which will not be easy to maintain.

There might be big problem, if value passed from external source is not available in drop down causes test script failure.

So the point is, if you do not require to select any specific value from drop down, you must select any random value. It will reduce the maintaining of test data in external files as well as unexpected test script failure.

How to select any random value from drop down:

  1. First identity what type of drop down it is.
  2. Get all options available in drop down.
  3. Generate a random number within 0 and number of options. You can set min and max as per your requirements.
  4. Select option available at random number position.

Example code:

Output: Run above program, you will see how different values are selected in drop down.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning