Reputation: 325
I need the java webdriver to click a button on a page wherever it is present. No fixed number of occurrences of the element but its not more than 20.
i tried using:
for(i=0; i<=20; i++){
try{
driver.findElement(By.cssSelector(".btn.btn-small.btn-list")).isDisplayed();
present = true;
} catch(Exception g) {
present = false;
}
if(present) {
driver.findElement(By.cssSelector(".btn.btn-small.btn-list")).click();
WaitForPageToLoad(5);
} else {
System.out.println(i);
break;
}
}
But this just works to click element 1 time, not for all occurrences. Please help.
Upvotes: 1
Views: 521
Reputation: 419
Here is another approach without using implicit waits but explicit which is more portable and maintainable when cross-browser and cross-platform testing. There is no need for your check to see if the element is visible/displayed as the WebDriverWait explicitly performs this for you.
See the following for more information on the different kinds of waits
String CSS_SELECTOR = ".btn.btn-small.btn-list";
webDriverWait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector(CSS_SELECTOR)))
List<WebElement> elements = driver.findElements(By.cssSelector(CSS_SELECTOR));
for ( WebElement element : elements ) {
element.click();
}
Upvotes: 0
Reputation: 29669
Here, try something like this:
boolean present = false;
List<WebElement> els= d.findElements( By.cssSelector(".btn.btn-small.btn-list"));
d.manage().timeouts().implicitlyWait( 10, TimeUnit.SECONDS );
for ( WebElement we : els ) {
try{
if ( we.isDisplayed() ) {
we.click();
present = true;
} else {
System.out.println("Invisible.");
}
} catch( StaleElementReferenceException|NoSuchElementException g) {
System.out.println("WARNING: " + g.getMessage() );
}
}
if ( present ) {
System.out.println("Found bookoo!");
} else {
System.out.println("Found nada!");
}
Upvotes: 1