0

I have the following code snippet

<div class="space-10"></div>
<form action="/book/index" method="post" class="form-inline" >
<div class="row no-margin no-padding">
<div class="form-group col-sm-3 col-xs-12 no-margin-padding">
   <select id="sport" name="sport" data-style="form-control">
      <option value="">Välj sport</option>
      <option value="1" 
         data-content="<i class='ma ma-Tennis'></i> Tennis">Tennis</option>
      <option value="2" 
         data-content="<i class='ma ma-Badminton'></i> Badminton">Badminton</option>
      <option value="3" 
         data-content="<i class='ma ma-Squash'></i> Squash">Squash</option>
      <option value="4" 
         data-content="<i class='ma ma-Bordtennis'></i> Bordtennis">Bordtennis</option>
      <option value="5" 
         data-content="<i class='ma ma-Padel'></i> Padel">Padel</option>
      <option value="6" 
         data-content="<i class='ma ma-Övrigt'></i> Övrigt">Övrigt</option>
      <option value="7" 
         data-content="<i class='ma ma-Pickleball'></i> Pickleball">Pickleball</option>
   </select>
</div>

And i want random selection of an item from list. I've tried all possible selectors but getting element not found error.

1
  • You can use Select class with value (write API to generate random number from 1 to 7). This should ideally address your requirement. Could you please share what selectors you have tried. Commented Aug 21, 2018 at 6:10

1 Answer 1

2

I hope my below code may help you:

Select dropdown = new Select(driver.findElement(By.id("id")));

//Get all options
List<WebElement> dd = dropdown.getOptions();
int index = 0;//if list contains only one element it will take that element
if(dd.size()>1){
   //Get a random number between 1, size of dd
    random rand = new Random();
    index = rand.nextInt(dd.size()-1);
 }else if(dd.size()<1){
    //print error message
     int = -1;
 }
 if (index >= 0){
     dropdown.selectByIndex(index);
 }
5
  • 1
    Your code misses some checks for dd.size() since if dd.size()-1 would be <=0 you will get an Exception in nextInt() Commented Aug 21, 2018 at 8:24
  • my intention is to give an idea of selecting random option, they need to take care of exceptions Commented Aug 21, 2018 at 12:22
  • 1
    Of course it is up to you how to give the answer. I'm just saying that your code will not work for size = 1 and it won't take much time to fix. Commented Aug 21, 2018 at 13:08
  • it will work for size = 1 , it will take the 0th index element when size is 1 Commented Aug 22, 2018 at 4:37
  • 1
    No, it will not. Have you ever tried to call new Random().nextInt(0)? Check this: docs.oracle.com/javase/8/docs/api/java/util/… Commented Aug 22, 2018 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.