Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using webdriver to see if an element exists WITHOUT throwing an exception?

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?

like image 535
user1282634 Avatar asked Mar 21 '12 06:03

user1282634


2 Answers

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;
}
like image 152
djangofan Avatar answered Oct 12 '22 22:10

djangofan


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:

  1. locator_keyword: {values : id or cssSelector or xpath etc}
  2. locator : {values : "q" }

Steps in method:

  1. Get element based on the locator_keyword and locator
  2. Check if element is there and click it
  3. Otherwise don't do anything

This method can be used as a generic kind of thing for any type of objects.

like image 32
Nayan Avatar answered Oct 12 '22 22:10

Nayan