I am trying to see if a particular element is displayed, then perform search for n times, else break loop, and continue with other actions in Selenium.
Once the row element is visible, the scripts stops instead of continuing with the code outside the loop.
Boolean row = driver.findElement(By.xpath("//*[contains(text(),'mytext')]")).isDisplayed();
if (row){
for (int i = 0; i < 50; i ){
Thread.sleep(1000);
action.sendKeys(Keys.TAB).build().perform();
Search.click();
if (row == false){
break;
}
}
}
driver.findElement(By.xpath(something)).click();
Once row element is visible scripts stop instead of continuing with code outside the loop.
CodePudding user response:
Basically issue is, You are using .isDisplayed();
which works well if the web element is found. It will return yes. If the web element is not displayed, mostly you are going to get no such element exception.
Unfortunately, .isDisplayed();
does not handle this exception effectively.
As a workaround, I would suggest using findElements
which will return a list of web elements if found, else return an empty list.
List<WebElement> rows = driver.findElements(By.xpath("//*[contains(text(),'mytext')]"));
if (rows.size() > 0){
System.out.println("row is visible");
for (int i = 0; i < 50; i ){
Thread.sleep(1000);
action.sendKeys(Keys.TAB).build().perform();
Search.click();
List<WebElement> rowsStatus = driver.findElements(By.xpath("//*[contains(text(),'mytext')]"));
if (rowsStatus.size() > 0 ) {
continue;
}
else {
System.out.println(" exiting the loop if rows is found in for loop early");
break;
}
}
}
else {
System.out.println("Row is not visible, do something here to make it visible.");
}
driver.findElement(By.xpath(something)).click();
CodePudding user response:
You should add this displaying function inside the for loop too. then only, loop will be broken.
// list of options which has more money
for (int i = 0; i < 50; i ){
Thread.sleep(1000);
action.sendKeys(Keys.TAB).build().perform();
Search.click();
row = driver.findElement(By.xpath("//*[contains(text(),'mytext')]")).isDisplayed();
if (row == false){
break;
}
}