Check if an element is present

Hi,

I am using appium to automate the testing of our iOs app. Tests are written in Java.

I am trying to check if an element is present. If yes, I want to click it, if not proceed with the rest of the test without failing my tests.

For example, when I am trying to launch the map, the first time I access the map feature, i get a pop-up if I want to let my app use Location services. This does not come up every time, but only the first time I try to use maps.

So if there is this pop-up, I want to click “ok”, else proceed with the rest of the tests. how do I do this?

If I check using appium.findElement(By.xpath(path)), it times out if the element is not present.

Regards,
Sangeetha

1 Like

H Sangeetha,
Currently I use below code to achieve such requirement

if(!driver.findElements(By.name(using)).isEmpty()) {

}

Replace “using” with the text you are looking for.

Please note you may want to add some delay or additional logic, before calling this method to make sure you don’t run this code before that element is displayed.

6 Likes

Why dont u override isElementPresent functions to ur code…

protected boolean isElementPresent(By by) {
  
  
    
    		try {
  
  
    
    			driver.findElement(by);
  
  
    
    			return true;
  
  
    
    		} catch (NoSuchElementException e) {
  
  
    
    			return false;
  
  
    
    		}
  
  
    
    	}

You can check implementation on below scripts.
https://github.com/priyankshah217/AppiumTestAutomation/blob/master/src/test/java/com/test/selendroid/app/screens/AbstractScreen.java

Thanks,
Priyank Shah

2 Likes

RamS solution is good. Basically you count the number of elements corresponding to your search criteria and check if it’s 0 or 1. Of course, try to identify an unique criteria.

Hi Ram,

Thanks a lot!! your proposed solution totally worked for me. I somehow missed this and was trying the findElement(), which used to fail if element is not found!

Not very critical, but do let me know if there is a way to reduce the default time until which findElements() keeps looking for the element.

Thanks again!
Sangeetha

Hi Sangeetha,

You can set implicit wait to zero to reduce the default time.

eg:

driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

1 Like

@Sangeetha
You can use the Selenium support library to achieve that easily

new WebDriverWait(_driver, 10000).until(ExpectedConditions.visibilityOfElementLocated(By.Id(“Element ID”)));

You can find it here

@Hassan_Radi Hey, not sure if it’s the best idea about 10000, don’t forget that timeout is in second.

   * @param driver The WebDriver instance to pass to the expected conditions
   * @param timeOutInSeconds The timeout in seconds when an expectation is called
   * @see WebDriverWait#ignoring(java.lang.Class)
   */
  public WebDriverWait(WebDriver driver, long timeOutInSeconds)

@Benoit
Sorry my bad, but you get the idea :smile:

Where to put this wait? Appium is always taking at least 2 minutes to find element.

This worked for me,

Thanks a lot

I got the solution for this post.

if(!driver.findElements(By.id(“com.test.mobiledemo:id/btn_no”)).isEmpty()) {
driver.findElement(By.id(“com.test.mobiledemo:id/btn_no”)).click();
}

	else
	{

	Thread.sleep(40000);
	driver.findElement(By.id("com.test.mobiledemo:id/img_cd_FrontImg")).click();

}

i am not able to use if(!driver.findElementByXPath(“//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAStaticText[7]”).isDisplayed())

throwing
5. Exception error ‘java.lang.IllegalArgumentException: No enum constant Utilities.Common.identifierType.//uiaapplication[1]/uiawindow[1]/uiascrollview[1]/uiawebview[1]/uiastatictext[@name

in the app this is only way to identify the element. cant find with other locators like name etc

@Sangeetha

I am using this method. Try this.

public static IOSElement waitForVisibleIosElement(final By by, int waitTime) { try { WebDriverWait wait = new WebDriverWait(iOSDriver, waitTime); wait.until(ExpectedConditions.elementToBeClickable(by)); return iOSDriver.findElement(by); } catch (org.openqa.selenium.TimeoutException e) { return null; } }

Hi,
I have a list of 5 elements. While clicking on first element and performing some changes to first element and after saving first element the second element is deleted automatically.
How to verify that second element is present or not because issue is “id” of all element is same .
while verifying through id it is giving me element is present.
Thanks.

Thanks , it works.
WebElement feedsCatItems = (new WebDriverWait(driver, 0)) .until(ExpectedConditions.presenceOfElementLocated(By.className(“android.view.View”)));
System.out.println(“view” +feedsCatItems.isDisplayed());

Thanks Ram. It’s working for me.

Hi,

Can some one help me out for my if else condition
like i am testing an app for location related listing
I have set location and there is a message which can be said as location is not valid
and then again if i have set the location invalid it should continue until the location is valid
like
if (popupdisplayed) is met
perform the set location
else
location is valid
if then too after location is set
but still popup is displayed
then i have to run again the step to set location

Regards,
Pratik.

Hi, in your case you can use fluent wait which in my opinion is very useful when you know how to use it.

 private FluentWait<AppiumDriver> fluentWait(MobileElement locator, int time) {
        return new FluentWait<>(AppiumController.instance.driver)
                .withTimeout(Duration.ofSeconds(time))
                .pollingEvery(POLLING_TIMEOUT) //Set query/check/control interval
                .ignoring(NoSuchElementException.class)
                .withMessage(locator + "is not displayed");
    }

and you can have 2 methods, one is only waiting until an element is clickable and another one is returning a boolean value if an element is displayed after a defined time

 public void waitForElement(MobileElement locator, int time) {
         try {
            logger.info("Checking the " + locator + "  having " + time + " seconds limit");
            fluentWait(locator, time).until(ExpectedConditions.elementToBeClickable(locator));
         } catch (TimeoutException | NoSuchElementException e) {
             logger.debug("The " + locator + " isn't clickable after timeout");
         }
    }

  public boolean isElementDisplayed(MobileElement locator, int time) {
         boolean status = true;
         try {
             logger.info("Checking the " + locator + "  having " + time + " seconds limit");
             fluentWait(locator, time).until(ExpectedConditions.elementToBeClickable(locator));
         } catch (TimeoutException e) {
             status = false;
         }
        return status;
    }