简体   繁体   中英

For loop in JAVA (Selenium) for findElement through cssSelector

I'd like to use for loop for these to click them from 1st checkbox - 4th checkbox for my test automation.

webdriver.findElement(By.cssSelector("#mat-checkbox-1 .mat-checkbox-inner-container")).click();
webdriver.findElement(By.cssSelector("#mat-checkbox-2 .mat-checkbox-inner-container")).click();
webdriver.findElement(By.cssSelector("#mat-checkbox-3 .mat-checkbox-inner-container")).click();
webdriver.findElement(By.cssSelector("#mat-checkbox-4 .mat-checkbox-inner-container")).click();

I've tried the code below but it's still not working.

for(int i=1; i>=4; i++){
webdriver.findElement(By.cssSelector("#mat-checkbox-"+i+".mat-checkbox-inner-container")).click();
}

First of all, your loop is not correct. The second condition is about when the loop should run, and since you have it as i>=4 and start at i=1 it would never run. Also, you should separate conditions with ; , so the correct for-loop in your case would be: for(int i = 1; i <= 4; i++){...} . And finally, you forgot the whitespace before .mat-checkbox-.. part. The correct code should look like this:

for(int i = 1; i <= 4; i++){
    webdriver.findElement(By.cssSelector("#mat-checkbox-"+i+" .mat-checkbox-inner-container")).click();
}

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