简体   繁体   中英

How to click on random item in the list Selenium Java

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
}

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();
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM