Web element in a for loop

372 Views Asked by At
for (int i = 1; i >=0 ; i--) {
    driver.findElement(By.cssSelector("form.form-inline > input:nth-of-type(1)")).sendKeys(n);
    Select option = new Select(driver.findElement(By.cssSelector("select")));
    option.selectByValue("MULTIPLICATION");
    driver.findElement(By.cssSelector("form.form-inline > input:nth-of-type(2)")).sendKeys(String.valueOf(i));
    driver.findElement(By.id("gobutton")).click();
    Thread.sleep(5000);

    /** vvv Line Below vvv **/
    String q =(driver.findElement(By.className("ng-binding")).getText());
}

The one I highlighted is changing each time the loop goes on. How can this save each time the text to a different string?

2

There are 2 best solutions below

0
On

By declaring a list of String and then adding text into it you can do it:

List<String> textList = new ArrayList<>();
for (int i = 1; i >=0 ; i--) {
driver.findElement(By.cssSelector("form.form-inline > input:nth-of-type(1)")).sendKeys(n);
Select option = new Select(driver.findElement(By.cssSelector("select")));
option.selectByValue("MULTIPLICATION");
driver.findElement(By.cssSelector("form.form-inline > input:nth-of-type(2)")).sendKeys(String.valueOf(i));
driver.findElement(By.id("gobutton")).click();
Thread.sleep(5000);

/** vvv Line Below vvv **/
String q =(driver.findElement(By.className("ng-binding")).getText());
textList.add(q);
}

Then you can get elements of list by running a loop. textList.get(0) will return the string element at the 0th index of the list.

Hope it helps you.

0
On

Create an ArrayList of String, like

List<String> list = new ArrayList<>();
for(int i=1;i>=0;i--){
    //do stuff
    list.add((driver.findElement(By.className("ng-binding")).getText()));
}
for(String s : list){
    System.out.println(s);
}