Check Visibility of Web Elements Using Various Types WebDriver Commands – Selenium Tutorial #14

How to check visibility of web elements using various types of looping and conditional commands in WebDriver:

Previously in the series, we discussed about WebDriver’s Select class which is primarily used to handle web elements like dropdowns and selecting various options under the dropdowns.

Moving ahead in the Selenium series, we would be discussing about the various types of looping and conditional commands in WebDriver like isSelected(), isEnabled() and isDispalyed(). These methods are used to determine the visibility scope for the web elements.

So let us start with a brief introduction – WebDriver has a W3C specification that details out the information about the different visibility preferences based out on the types of the web elements upon which the actions are to be performed.

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, dropboxes, checkboxes, radio buttons, labels etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()

For an improved understanding, let us discuss the aforementioned methods with code examples.

As a specimen, we would be using the “google.com” as an application under test and the “Learning_Selenium” project created in the previous tutorials for script generation.

Scenario to be automated

  1. Launch the web browser and open the application under test – http://google.com
  2. Verify the web page title
  3. Verify if the “Google Search” button is displayed
  4. Enter the keyword in the “Google Search” text box by which we would want to make the request
  5. Verify that the “Search button” is displayed and enabled
  6. Based on visibility of the Search button, click on the search button

WebDriver Code

Step 1: Create a new java class named as “VisibilityConditions” under the “Learning_Selenium” project.

Step 2: Copy and paste the below code in the “VisibilityConditions.java” class.

Below is the test script that is equivalent to the above mentioned scenario:

 import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class VisibilityConditions {

       /**
        * @param args
        */

       public static void main(String[] args) {

              // objects and variables instantiation
              WebDriver driver = new FirefoxDriver();
              String appUrl = "https://google.com";

              // launch the firefox browser and open the application url
              driver.get(appUrl);

              // maximize the browser window
              driver.manage().window().maximize();

              // declare and initialize the variable to store the expected title of the webpage.
              String expectedTitle = "Google";

              // fetch the title of the web page and save it into a string variable
              String actualTitle = driver.getTitle();

              // compare the expected title of the page with the actual title of the page and print the result
              if (expectedTitle.equals(actualTitle))
              {
                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
              }
              else
              {
                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
              }

              // verify if the “Google Search” button is displayed and print the result
              boolean submitbuttonPresence=driver.findElement(By.id("gbqfba")).isDisplayed();
              System.out.println(submitbuttonPresence);

              // enter the keyword in the “Google Search” text box by which we would want to make the request
              WebElement searchTextBox = driver.findElement(By.id("gbqfq"));
              searchTextBox.clear();
              searchTextBox.sendKeys("Selenium");

              // verify that the “Search button” is displayed and enabled
              boolean searchIconPresence = driver.findElement(By.id("gbqfb")).isDisplayed();
              boolean searchIconEnabled = driver.findElement(By.id("gbqfb")).isEnabled();

              if (searchIconPresence==true && searchIconEnabled==true)
              {
                     // click on the search button
                     WebElement searchIcon = driver.findElement(By.id("gbqfb"));
                     searchIcon.click();
              }

              // close the web browser
              driver.close();
              System.out.println("Test script executed successfully.");

              // terminate the program
              System.exit(0);
       }
} 

 

Code Walkthrough

------------

Following are the ways in which we ascertain the presence of web elements on the web page.

boolean submitbuttonPresence=driver.findElement(By.id(“gbqfba”)).isDisplayed();

isDispalyed()

isDisplayed() is the method used to verify presence of a web element within the webpage. The method is designed to result a Boolean value with each success and failure. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.

Thus the above code snippet verifies for the presence of submit button on the google web page and returns a true value if the submit button is present and visible else returns a false value if the submit button is not present on the web page.

boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

The method deals with the visibility of all kinds of web elements not just limiting to any one type.

isEnabled()

isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage. Like isDisplayed() method, it is designed to result a Boolean value with each success and failure. The method returns a “true” value if the specified web element is enabled on the web page and a “false” value if the web element is not enabled (state of being disabled) on the web page.

Thus the above code snippet verifies if the submit button is enabled or not and returns a Boolean value depending on the result.

The isEnabled() method is significant in scenarios where we want to ascertain that only if “Condition A” is fulfilled, then the element(principally button) is enabled. Refer the following illustration for the same.

Webdriver commands 1

In the above figure, Register button button is enabled only when the agreement checkbox is selected.

Akin to above methods, we have a method referenced as “isSelected()” which tests if the specified web element is selected or not.

boolean searchIconSelected = driver.findElement(By.id(“male”)).isSelected();

isSelected()

isSelected() is the method used to verify if the web element is selected or not. isSelected() method is pre-dominantly used with radio buttons, dropdowns and checkboxes. Analogous to above methods, it is designed to result a Boolean value with each success and failure.

Thus the above code snippet verifies if the male radio button is selected or not and returns a Boolean value depending on the result. Refer the following image for the same.

Conclusion

In this tutorial, we tried to make you acquainted with the WebDriver’s looping and conditional operations. These conditional methods often deal with almost all types of visibility options for web elements.

Article Summary:

  • WebDriver has a W3C specification that details out the information about the different visibility preferences based out on the types of the web elements.
  • isDisplayed() is the method used to verify presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.
  • isDisplayed() is capable to check for the presence of all kinds of web elements available.
  • isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage.
  • isEnabled() is primarily used with buttons.
  • isSelected() is the method used to verify if the web element is selected or not. isSelected() method is pre-dominantly used with radio buttons, dropdowns and checkboxes.

Next Tutorial #15: While working on web applications, often we are re-directed to different web pages by refreshing the entire web page and re-loading the new web elements. At times there can be Ajax calls as well. Thus, a time lag can be seen while reloading the web pages and reflecting the web elements. Thus, our next tutorial in-line is all about dealing with such time lags by using implicit and explicit waits.

Note for the Readers: Till then, the reader can automate and test the visibility scope for the web elements using WebDriver’s methods.




16 comments ↓

#1 QTP Tutorial

Another great tutorial on some very useful Selenium methods.

#2 Rohit

Thanks for sharing. very useful one.

#3 Shruti Shrivastava

@Rohit

Thank you for your kind words.

#4 Tanushri

I tried executing the above script but can see following error. Please help me to resolve this.

Exception in thread “main” org.openqa.selenium.WebDriverException: f.QueryInterface is not a function
Command duration or timeout: 31 milliseconds
Build info: version: ‘2.44.0’, revision: ’76d78cf’, time: ‘2014-10-23 20:03:00’
System info: host: ‘sys’, ip: ‘14.96.67.198’, os.name: ‘Windows 7’, os.arch: ‘x86’, os.version: ‘6.1’, java.version: ‘1.7.0_71’
Session ID: 27771a7c-495b-4f26-8ff2-b97d3ab4d2b6
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=true, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=33.1}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:304)
at Selenium.VisibilityConditions.main(VisibilityConditions.java:19)
Caused by: org.openqa.selenium.WebDriverException: f.QueryInterface is not a function
Build info: version: ‘2.44.0’, revision: ’76d78cf’, time: ‘2014-10-23 20:03:00’
System info: host: ‘sys’, ip: ‘14.96.67.198’, os.name: ‘Windows 7’, os.arch: ‘x86’, os.version: ‘6.1’, java.version: ‘1.7.0_71’
Driver info: driver.version: unknown
at .FirefoxDriver.prototype.get(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:9504:13)
at .DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11635:16)
at .DelayedCommand.prototype.executeInternal_(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11640:7)
at .DelayedCommand.prototype.execute/<(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11582:5)

#5 Vishal Khatri

Which language is good for selenium ? java or java script ?

#6 Dave Peterson

When I tried to execute this tutorial with the original script as such:

// verify if the “Google Search” button is displayed and print the result
boolean submitbuttonPresence=driver.findElement(By.id(“gbqfba”)).isDisplayed();
System.out.println(submitbuttonPresence);

It yielded the following partial result log:

Verification Successful – The correct title is displayed on the web page.
Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”id”,”selector”:”gbqfba”}

A quick inspection of the page showed that the Google Search button was not using the ‘id’ property (they must have changed it), but it appears that they are using the ‘name’ property. So I modified the sample code, changing the search property and adding an identifying string to the result:

// verify if the “Google Search” button is displayed and print the result
boolean submitbuttonPresence=driver.findElement(By.name(“btnK”)).isDisplayed();
System.out.println(“submitbuttonPresence:” + submitbuttonPresence);

As you can see by the following partial result log, the Google Search button has now been correctly identified, but the script now fails on the next element:

Verification Successful – The correct title is displayed on the web page.
submitbuttonPresence:true
Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”id”,”selector”:”gbqfq”}

This illustrates what has always been my biggest problem with Selenium. It seems the most common practice for scripting Selenium test programs is to capture web objects just before you need to make reference to them. This, in my never-to-be-humble opinion, is extremely poor practice for a couple reasons:

1. If the identification for an on-screen object is changed by the developers (and it inevitably will change), you need to dig through the test script to find the object reference and change the search properties. Hopefully you edit the correct object reference.
Hopefully you correct ALL the object references for this object.
When the dev staff changes the UI again (which they will), you get to do it all over again!

2. The test procedure you’re trying to execute is polluted with all this superfluous, garbage code that exists ONLY to find the stupid button (or whatever object) on the page! It has NOTHING to do with the actual test procedure being performed. This obscures the intention of the test program.

Most of the purchased testing systems have some sort of object library function. In QTP it’s called the Object Repository (although HP rendered the function useless in version 10), and in TestComplete it’s called the NameMapping object. The purpose of such structures is
to gather together all objects that test scripts will require, give them an easily identified reference name (What the heck is “gbqfba”?) in a sharable library. When the identification properties change for a given object, only one reference needs to be updated. If the
logic of the function hasn’t changed, the test will continue to operate with no other revisions required.

Similar functionality could (and I argue, it should) be implemented in Selenium, but I’ve never seen it scripted that way. I will never understand why not.

#7 rochak bhalla

Thanks a lot, it really means a lot for someone who really wanted to bring in selenium webdriver in practice without any prior knowledge. Really Helpful again thanks

#8 Pankaj Sharma

Great effort by you Shruti; i really appreciate it. Have became fan of you :)

#9 bhupen

in selenium webdriver, if i select dropdown value by ‘name'(eg. price low to high, high to low) then how do i verify that all products(GUI) are sorted by name or not?

#10 Gaurav

Thanks for sharing.

@tanushree- U have to provide complete URL like http://www.google.com.

#11 Raj N

Hi everyone,

if the example script is not working… which means we have to troubleshoot and correct it… I tried and figured out and made some changes to the script , its working..
The changes are instead of web element locator By.id I used By.name.
Hope it helps .. just copy and paste and run it…
here is the working script for the above example:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class VisibilityConditions {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// objects and variables instantiation
WebDriver driver = new FirefoxDriver();
String appUrl = “https://google.com”;
// launch the firefox browser and open the application url
driver.get(appUrl);
// maximize the browser window
driver.manage().window().maximize();
// declare and initialize the variable to store the expected title of the webpage.
String expectedTitle = “Google”;
// fetch the title of the web page and save it into a string variable
String actualTitle = driver.getTitle();
// compare the expected title of the page with the actual title of the page and print the result
if (expectedTitle.equals(actualTitle))
{
System.out.println(“Verification Successful – The correct title is displayed on the web page.”);
}
else
{
System.out.println(“Verification Failed – An incorrect title is displayed on the web page.”);
}
// verify if the “Google Search” button is displayed and print the result
boolean submitbuttonPresence=driver.findElement(By.name(“btnK”)).isDisplayed();
System.out.println(submitbuttonPresence);

// enter the keyword in the “Google Search” text box by which we would want to make the request
WebElement searchTextBox = driver.findElement(By.id(“lst-ib”));
searchTextBox.clear();
searchTextBox.sendKeys(“Selenium”);
Thread.sleep(1000);
// verify that the “Search button” is displayed and enabled
boolean searchIconPresence = driver.findElement(By.name(“btnG”)).isDisplayed();
boolean searchIconEnabled = driver.findElement(By.name(“btnG”)).isEnabled();

if (searchIconPresence==true && searchIconEnabled==true)

{
// click on the search button

WebElement searchIcon = driver.findElement(By.name(“btnG”));

searchIcon.click();

}
// close the web browser
driver.close();
System.out.println(“Test script executed successfully.”);
// terminate the program
System.exit(0);
}
}

#12 rahul G

# error is the above content . Isdisplayed() returns true if element is present( checks element is visible not hidden) if element is not present it will not return false . It will return NosuchElement found exception . It must be included in the try catch block

public void deleteSubVar() throws Exception
{
try
{
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**when the element is found do this*/
}
}
catch(Exception e)
{
/**include the else part here*/
}
}

#13 Gaurav Khurana

all your artciles are so nice Shruti. Working great, My suggestion would be to include some assignments at the end of each tutorial.

#14 liki

how to test whether the sent mail is inside sent mail label or not using selenium webdriver

#15 rt

Hi,

Can you please help me on how to find a disabled element(greyed out text box) on webpage through xpath.

#16 Daniel Trujillo Arévalo

Hi, guys. i just found that the ids used in this example are not up to date. i change the id references to name references in the below code it works correctly.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

public class VisibilityConditions {

public static void main(String[]args)
{
//objects and varaibles
WebDriver driver = new FirefoxDriver();
String appUrl= “https://google.com”;

//launch the firefox browser and open the URL

driver.get(appUrl);
//maximize window
driver.manage().window().maximize();

//expected title
String expectedTitle =”Google”;
String actualTitle= driver.getTitle();
//fetch title on the web site
if (expectedTitle.equals(actualTitle))
{
System.out.println(“Verification successful – correct title displayed”);

}
else
{
System.out.println(“Verification Failed – An Incorrect title is displayed”);
System.out.println(actualTitle);

}
//verify if the “google search button is displayed”
boolean submitbuttonPresence=driver.findElement(By.name(“btnK”)).isDisplayed();
System.out.println(submitbuttonPresence);

//enter keyword in the “Google Search” text box
WebElement searchTexbox = driver.findElement(By.id(“lst-ib”));
searchTexbox.clear();
searchTexbox.sendKeys(“Selenium”);

//verify that the search button is displayed and enabled
boolean searchIconPresence = driver.findElement(By.name(“btnK”)).isDisplayed();
boolean searchIconEnabled=driver.findElement(By.name(“btnK”)).isEnabled();

if (searchIconPresence==true && searchIconEnabled==true)

{
//click on search button

WebElement searchIcon = driver.findElement(By.name(“btnK”));
searchIcon.click();
}

//Close the browser

driver.close();
System.out.println(“Test script executed successfully.”);
//terminate the program

}
}

Leave a Comment