Home > Enterprise >  How to click on random item in the list Selenium Java
How to click on random item in the list Selenium Java

Time:09-30

Sorry for this question, I understand, for somebody this is easy, but I need help

For example I have:

@FindBy(xpath="example")
private List<WebElement> exampleList;

And I need to click on the random item in the list:

public void clickOnRandomItemInList() {
    exampleList.get(i).click; //how I can randomize "I"
}

I tried this one:

Random randomize = new Random()
public void clickOnRandomItemInList() {
    exampleList.get(randomize.nextInt(exampleList.size)).click; //but this way doesn't work
}

CodePudding user response:

You can do it as following:
Get a random index according to the List size, get element from the List accordingly and click it.

public void clickOnRandomItemInList(){
    Random rnd = new Random();
    int i = rnd.nextInt(exampleList.size());
    exampleList.get(i).click();
}

CodePudding user response:

We need to determine lower limit and upper limit and then generate a number in between.

lower limit we will set to 1, cause we at least wanna deal with 1 web element.

upper limit we will use list size, int high = exampleList.size();

Now using the below code

Random r = new Random();
int low = 1;
int high = exampleList.size();
int result = r.nextInt(high-low)   low;

and now call this method

public void clickOnRandomItemInList() {
    Random r = new Random();
    int low = 1;
    int high = exampleList.size();
    int result = r.nextInt(high-low)   low;
    exampleList.get(result).click; 
}

PS low is (inclusive) and high is (exclusive)

  • Related