I am new to Selenium webdriver, maybe this question is obvious. I am after situation like this:
If the element exists, click it and go back to index page:
driver.findElement(By.id("...."])).click();
if doesn't exit, skip it and go back to index page. The test still goes on without any exception thrown.
I know one solution to this:
driver.findElements( By.id("...") ).size() != 0
so i tried:
if(driver.findElements(By.id("....")).size() > 0)
{
driver.findElement(By.id("....")).click();
driver.findElement(By.cssSelector("...")).click();
}
else
{
driver.findElement(By.cssSelector("....")).click();
}
This turned out really ugly though because if I have 10 elements to verify, this IF condition needs to be written 10 times.
Any workaround to make it neat?
There are ways to find elements without throwing exceptions by using try-catch conditions inside of loops. For example, this method I wrote (which can be simplified depending on what you use if for) will return a WebElement and it makes sure that it's clickable before returning it to you:
public static WebElement getElementByLocator( By locator ) {
driver.manage().timeouts().implicitlyWait( 5, TimeUnit.SECONDS );
WebElement we = null;
boolean unfound = true;
int tries = 0;
while ( unfound && tries < 10 ) {
tries += 1;
try {
we = driver.findElement( locator );
unfound = false; // FOUND IT
} catch ( StaleElementReferenceException ser ) {
unfound = true;
} catch ( NoSuchElementException nse ) {
unfound = true;
} catch ( Exception e ) {
staticlogger.info( e.getMessage() );
}
}
driver.manage().timeouts().implicitlyWait( DEFAULT_IMPLICIT_WAIT,
TimeUnit.SECONDS );
return we;
}
Solution could be many but that may hinder your architecture.
So easiest solution could be as follows:
Just create a method like optionalClick()
in some utility class or somewhere with the arguments as:
locator_keyword
: {values : id or cssSelector or xpath etc} locator
: {values : "q" } Steps in method:
locator_keyword
and locator
This method can be used as a generic kind of thing for any type of objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With