How to select any random value from a dropdown?

后端 未结 4 1114
迷失自我
迷失自我 2021-01-21 18:57

I am working on selenium using Java. In my application I want to select any random value from the dropdown. Please tell how is it possible?

相关标签:
4条回答
  • 2021-01-21 19:06

    Use getSelectOptions to get an array of options of the select box.

    Then generate a random integer between 0 (inclusive) and the length of the array (exclusive).

    Then use select with an index locator to select the randomly chosen option.

    0 讨论(0)
  • 2021-01-21 19:18

    First generate a random number between 0 and the number of items in your list. For example:

    int random = new Random().nextInt(5);
    

    Then use this random number as the index in your select call:

    select("mydropdown", "index=" + random);
    
    0 讨论(0)
  • 2021-01-21 19:19

    What Sachin said. I know often it's good to get an actual code reply, so assuming you're working with a JComboBox:

    comboBox.setSelectedIndex(new Random().nextInt(comboBox.getItemCount()));

    The class Random can be found in the java.util package.

    0 讨论(0)
  • 2021-01-21 19:23

    Well, first get the total number of items in the dropdown. Then generate a random number between 0 and dropdown items count. Then select that number as index to set your dropdown item

    0 讨论(0)
提交回复
热议问题