Quick Contact

    Wait

    Waiting is having the automated task execution elapse a certain amount of time before continuing with the next step. It provides some slack between actions performed, in selenium slack between locating an element or any other operation with the element. The wait is mostly used to handle the ElementNotVisibleException exception during load of web page. Waits help a user to troubleshoot issues while re-directing 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.

    Selenium WebDriver provides the user with two types of waits in order to handle the recurring page loads, web element loads, the appearance of windows, pop ups and error messages and reflection of web elements on the web page.

    • Implicit wait: An implicit wait makes WebDriver poll the DOM for a certain amount of time when trying to locate an element.
    • Explicit wait. An explicit wait makes WebDriver wait for a certain condition to occur before proceeding further with execution.
    Implicit Wait

    Implicit waits are used to provide a default waiting time between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.

    The implicit wait is a single line of a code and can be declared in the setup method of the test script. However, Implicit wait time increases test script execution time as each of the commands would be ceased to wait for a stipulated amount of time before resuming the execution.

    The Syntax of Implicit wait is:

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

    The above line of code shall be included into test script soon after instantiation of WebDriver instance variable. The first argument indicates the time in the numeric digits that the system needs to wait. The second argument indicates the time measurement scale in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS.

    For using implicit waits in the test scripts, it’s mandatory to import the following package.

    import java.util.concurrent.TimeUnit;
    Explicit Wait

    Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, Explicit waits are applied for a particular instance only. The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an “ElementNotVisibleException” exception.

    The following are the Expected Conditions that can be used in Explicit Wait:

    • alertIsPresent()
    • elementSelectionStateToBe()
    • elementToBeClickable()
    • elementToBeSelected()
    • frameToBeAvaliableAndSwitchToIt()
    • invisibilityOfTheElementLocated()
    • invisibilityOfElementWithText()
    • presenceOfAllElementsLocatedBy()
    • presenceOfElementLocated()
    • textToBePresentInElement()
    • textToBePresentInElementLocated()
    • textToBePresentInElementValue()
    • titleIs()
    • titleContains()
    • visibilityOf()
    • visibilityOfAllElements()
    • visibilityOfAllElementsLocatedBy()
    • visibilityOfElementLocated()

    The Syntax of Explicit wait is:

    WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
    WebDriverWait wait=new WebDriverWait(driver, 20);
    WebElement element = 
    wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")))
    ;
    

    Example:

    WebElement Testseleniumlink; 
    Testseleniumlink=
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xp ath( "/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/di v/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i")));
    Testseleniumlink.click();
    

    In the above example, wait for the amount of time defined in either the “WebDriverWait” class or the “ExpectedConditions” to occur, whichever occurs first.

    The above code states that to wait for an element for the time frame of 20 seconds as defined in the “WebDriverWait” class on the webpage until the “ExpectedConditions” are met and the condition is “visibilityofElementLocated”.

    Fluent Wait

    The fluent wait is used to tell the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an “ElementNotVisibleException” exception. Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. A user may configure the wait to ignore specific
    types of exceptions whilst waiting, such as ‘NoSuchElementExceptions’ when searching for an element on the page.

    The Syntax of Fluent wait is:

    Wait wait = new FluentWait(WebDriver reference)
    .withTimeout(timeout, SECONDS)
    .pollingEvery(timeout, SECONDS)
    .ignoring(Exception.class);
    

    Example:

    WebElement Testseleniumlink; 
    Testseleniumlink=
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath( "/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/ div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i")));
    Testseleniumlink.click();
    

    In the above example, wait for the amount of time defined in either the “WebDriverWait” class or the “ExpectedConditions” to occur, whichever occurs first.

    The above code states that to wait for an element for the time frame of 20 seconds as defined in the “WebDriverWait” class on the webpage until the “ExpectedConditions” are met and the condition is “visibilityofElementLocated”.

    WebDriverWait and its Uses

    Waits help the user to troubleshoot issues while re-directing to different web pages by refreshing the entire web page and re-loading the new web elements. WebDriver equips the user to handle the recurring page loads, web element loads, the appearance of windows, pop ups and error messages and reflection of web elements on the web page.

    WebDriverWait class can be used in many different cases. Whenever there is a need to perform any operation on element, webdriver wait can be used to check if the element is present or visible or enabled or disabled or clickable.

    The various scenarios where to use webDriverWait are:

    • isElementPresent: It is used to check for the element presence on the DOM of a page. ExpectedConditions will return true once the element is found in the DOM.
    • isElementClickable: It is used to check if an element is visible and enabled such that element can be click.
    • isElementVisible: It is used to check if the element is present and visible on the DOM of a page and visible. Visibility means that the element is not just displayed but also should has a height and width that is greater than 0.
    • isElementInVisible: It is used to check if an element is either invisible or not present on the DOM.
    • isElementEnabled: It is used to check if the element is enabled.
    • isElementDisplayed: It is used to check if the element is displayed or not. It returns false when the element is not present in DOM.
    Different Wait Until Conditions

    ExpectedConditions class provides a great help to deal with scenarios where it is ascertain for a condition to occur before executing the actual test step. The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an “ElementNotVisibleException” exception.

    The following are the Expected Conditions that can be used in Explicit Wait:

    • alertIsPresent()
    • elementSelectionStateToBe()
    • elementToBeClickable()
    • elementToBeSelected()
    • frameToBeAvaliableAndSwitchToIt()
    • invisibilityOfTheElementLocated()
    • invisibilityOfElementWithText()
    • presenceOfAllElementsLocatedBy()
    • presenceOfElementLocated()
    • textToBePresentInElement()
    • textToBePresentInElementLocated()
    • textToBePresentInElementValue()
    • titleIs()
    • titleContains()
    • visibilityOf()
    • visibilityOfAllElements()
    • visibilityOfAllElementsLocatedBy()
    • visibilityOfElementLocated()
    Alerts

    Alert is a small message box which displays on-screen notification to give the user information or ask for permission to perform certain kind of operation. It may be also used for warning purpose. For
    e.g. a alert pop up window can be displayed if a user clicked on a button that displayed a message or may be when something is entered a form and HTML page requires some extra information.

    Alerts are blocking in nature and will not allow any action on the underlying webpage if present. So if an alert is present on the webpage and access any of the element in the underlying page will get UnhandledAlertException exception ie. “Modal dialog present”.

    There are three broad category of alerts as below:

    • Simple Alert: The simple alert displays some information or warning on the screen.
    • Prompt Alert: The prompt Alert asks some input from the user
    • Confirmation Alert: The confirmation alert asks permission to do some type of operation.
    Ways to Handle Simple, Confirmation and Prompt Alert

    Selenium provides an interface called Alert and is present in the org.openqa.selenium.Alert package. Alert interface provides following methods to handle alerts:

    • void dismiss(): The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
    • void accept(): The accept() method clicks on the “Ok” button as soon as the pop up window appears.
    • String getText(): The getText() method returns the text displayed on the alert box.
    • void sendKeys(String stringToSend): The sendKeys() method enters the specified string pattern into the alert box.
    Simple alert

    Simple alerts have an OK button on them. They are used to display some information to the user. The first alert on our test page is a simple alert.

    Example:

    Below code will read the text from the Alert and then accept the alert. The driver.switchTo().alert() is used to switch from main window to an alert.

    public static void main(String[] args) { 
    WebDriver driver = new FirefoxDriver();
    driver.get("http://toolsqa.wpengine.com/handling-alerts-using- selenium-webdriver/");
    driver.manage().window().maximize();
    
    // This step will result in an alert on screen
    driver.findElement(By.xpath("//*[@id='content']/p[4]/button"))
    .click();
    Alert simpleAlert = driver.switchTo().alert(); 
    String alertText = simpleAlert.getText(); 
    System.out.println("Alert text is " + alertText); 
    simpleAlert.accept();
    
    }
    
    Confirmation Alert

    Confirmation alert provides an option to accept or dismiss the alert to a user.

    Example:

    public static void main(String[] args) { 
    WebDriver driver = new FirefoxDriver();
    driver.get("http://toolsqa.wpengine.com/handling-alerts-using- selenium-webdriver/");
    driver.manage().window().maximize();
    // This step will result in an alert on screen 
    WebElement element =
    driver.findElement(By.xpath("//*[@id='content']/p[11]/button")
    );
    ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);
    Alert confirmationAlert = driver.switchTo().alert(); 
    String alertText = confirmationAlert.getText(); 
    System.out.println("Alert text is " + alertText); 
    confirmationAlert.dismiss();
    }
    
    Prompt Alerts

    The prompt alerts provides an option to add text to the alert box to get some input.

    Example:

    public static void main(String[] args) throws 
    InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://toolsqa.wpengine.com/handling-alerts-using- selenium-webdriver/");
    driver.manage().window().maximize();
    // This step will result in an alert on screen 
    WebElement element =
    driver.findElement(By.xpath("//*[@id='content']/p[16]/button")
    );
    ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);
    Alert promptAlert	= driver.switchTo().alert(); 
    String alertText = promptAlert .getText(); 
    System.out.println("Alert text is " + alertText);
    //Send some text to the alert
    promptAlert .sendKeys("Accepting the alert");
    Thread.sleep(4000); 
    //This sleep is not necessary, just for demonstration
    promptAlert .accept();
    
    }
    
    Switch Windows

    Selenium WebDriver provides switchto() method for switching between windows and frames. A switching to a window refers to an interaction with a new windows that open ups when a user clicks on a certain link or button. For example, a new window can open up for login, sign-up button.
    Alternatively, the switching method is used to handle multiple windows. The Syntax of switchto()
    method is

    driver.switchTo().window();
    Different Between Window Handle and Handles

    The Selenium Web Driver assigns an alphanumeric id to each window as soon as the Web Driver object is instantiated. This unique alphanumeric id is called window handle. Selenium uses this unique id to switch control among several windows.

    • GetWindowHandle(): This method is used to get the window handle of the current window. It returns a string of alphanumeric window handleExample:
      String	handle= driver.getWindowHandle();
    • GetWindowHandles(): This method is used to get the window handle of the all the current windows. It returns a set of window handleExample:
      Set<String> handle= driver.getWindowHandles();

    Selenium WebDrives use switchto() method to handle switch between windows by using
    GetWindowHandle() and GetWindowHandles() method.

    Example of usage of GetWindowHandle() to support moving between named windows.

    driver.switchTo().window("windowName");

    Alternatively, the a “window handle” can be passwed to the “switchTo().window()” method to iterate over every open window as below

    for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle);}

    Selenium WebDrives use Iterators with windows to iterate over every open window as below:

    Example:

    driver.findElement(By.id(“id of the link which opens new window”)).click();
    //wait till two windows are not opened
    waitForNumberofWindowsToEqual(2);
    //this method is for wait
    Set handles = driver.getWindowHandles();
    firstWinHandle = driver.getWindowHandle(); 
    handles.remove(firstWinHandle);
    String winHandle=handles.iterator().next(); 
    if (winHandle!=firstWinHandle){
    //To retrieve the handle of second window, extracting the handle which does not match to first window handle
    secondWinHandle=winHandle; //Storing handle of second window handle
    //Switch control to new window 
    driver.switchTo().window(secondWinHandle);
    
    Switching and Closing Windows, Tabs and Popups
    Switching between windows

    In order to shift focus from Parent Window to any child window, WebDriver use command WebDriver.SwitchTo().window(String windowHandle). This command takes in a window handle and switches the driver context on other window. Once the Switch happens all the driver commands will go to the newly focused window.

    Example:

    public static void main(String[] args) throws 
    InterruptedException
    {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://toolsqa.wpengine.com/automation-practice- switch-windows/");
    String parentWindowHandle = driver.getWindowHandle();
    System.out.println("Parent window's handle -> " + parentWindowHandle);
    WebElement clickElement = driver.findElement(By.id("button1"));
    for(int i = 0; i < 3; i++)
    {
    clickElement.click(); 
    Thread.sleep(3000);
    }
    Set<String> allWindowHandles = driver.getWindowHandles(); 
    for(String handle : allWindowHandles)
    {
    System.out.println("Switching to window - > " + handle);
    System.out.println("Navigating to google.com");
    driver.switchTo().window(handle); 
    //Switch to the desired window first and then execute commands using driver
    driver.get("http://google.com");
    
    }
    }
    
    Switching between Tabs

    switchto() method is used to switch between frames.

    Example:

    ArrayList<string> tabs = new 
    ArrayList<string> 
    (driver.getWindowHandles());
    //Switch to new window 
    driver.switchTo().window(tabs.get(1)); 
    driver.close();//do some action in new window(2nd tab)
    //Switch to main/parent window 
    driver.switchTo().window(tabs.get(0)); 
    driver.getTitle();//do some action in main window(1st tab)
    </string></string>
    
    Switching between Popups

    Switchto() method is used to support moving between named PopUps. After action is triggered that opens a popup, the alert can be accessed of the currently open alert object. This object is used to accept, dismiss, read its contents or even type into a prompt.

    Example:

    Alert alert = driver.switchTo().alert();
    Closing all the Windows

    WebDriver use WebDriver.close() and WebDriver.quit() commands to close the opened browser windows. These commands close the current window on which the focus is present. One can use switchto() command to select the correct windows and then call the WebDriver.close command.

    The WebDriver.quit() closes all the windows opened in the session. This command shuts down the driver instance and any further commands to WebDriver results in exception.

    Example:

    In the code below the parent window will be close and then explicitly move focus to the last window in the list.

    public static void main(String[] args) throws InterruptedException
    {
    WebDriver driver = new FirefoxDriver();
     
    driver.get("http://toolsqa.wpengine.com/automation- practice-switch-windows/");
    String parentWindowHandle = driver.getWindowHandle();
    System.out.println("Parent window's handle -> " + parentWindowHandle);
    WebElement clickElement = driver.findElement(By.id("button1"));
    for(int i = 0; i < 3; i++)
    {
    clickElement.click(); Thread.sleep(3000);
    }
    Set<String> allWindowHandles = driver.getWindowHandles(); 
    String lastWindowHandle = "";
    for(String handle : allWindowHandles)
    {
    System.out.println("Switching to window - > " + handle);
    System.out.println("Navigating to google.com");
    driver.switchTo().window(handle); 
    //Switch to the desired window first and then execute commands using driver
    driver.get("http://google.com"); lastWindowHandle = handle;
    }
    //Switch to the parent window 
    driver.switchTo().window(parentWindowHandle);
    //close the parent window driver.close();
    //at this point there is no focused window, it have to explicitly switch back to some window.
    driver.switchTo().window(lastWindowHandle);
    driver.get("http://toolsqa.wpengine.com");
    
    }
    
    Concepts of Set Interface in Java

    A Set is a Collection that can’t contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

    The various methods declared by Set are as below:

    • add( ): It adds an object to the collection.
    • clear( ): It removes all objects from the collection.
    • contains( ): It returns true if a specified object is an element within the collection.
    • isEmpty( ): It returns true if the collection has no elements.
    • iterator( ): It returns an Iterator object for the collection, which may be used to retrieve an object.
    • remove( ): It removes a specified object from the collection.
    • size( ): It returns the number of elements in the collection.

    Example:

    import java.util.*; 
    public class SetDemo {
    public static void main(String args[]) { int count[] = {34, 22,10,60,30,22};
    Set<Integer> set = new HashSet<Integer>(); 
    try {
    for(int i = 0; i < 5; i++) { set.add(count[i]);
    }
    System.out.println(set);
    
    TreeSet sortedSet = new TreeSet<Integer>(set); 
    System.out.println("The sorted list is:"); 
    System.out.println(sortedSet);
    System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
    System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
    }
    catch(Exception e) {}
    }
     
    }
    

    Output

    [34, 22, 10, 60, 30]
    The sorted list is: 
    [10, 22, 30, 34, 60]
    The First element of the set is: 10
    The Last element of the set is: 60
    
    Concept of Window ID

    Selenium WebDriver assigns an alphanumeric id to each window as soon as the WebDriver object is instantiated. This unique alphanumeric id is called window handle. Selenium uses this unique id to switch control among several windows. In simple terms, each unique window has a unique ID, so that Selenium can differentiate when it is switching controls from one window to the other.

    Javascript and Selenium

    JavaScript is the preferred language inside the browser to interact with HTML. There is no separate code required to execute the Java Script in WebDriver Script as Selenium provides predefined interface JavascriptExecutor. Inside this Interface the executeScript() method executes the Java Script which is passed as a String. The return values can be Boolean, Long, String, List, WebElement

    Syntax:
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript(Script,Arguments);
    
    Example:

    To click in Selenium if button or radio button is disable:

    import org.openqa.selenium.JavascriptExecutor; 
    import org.openqa.selenium.firefox.FirefoxDriver; 
    public class TestFirefox {
    public static void main(String[] args) throws 
    InterruptedException {
    // Open Firefox browser
    FirefoxDriver driver=new FirefoxDriver();
    
    // Maximize the window 
    driver.manage().window().maximize();
    // Open applicatiion
    driver.get("enter your application URL");
    // This will execute JavaScript in your script
    ((JavascriptExecutor)driver).executeScript("document.getElemen tById('enter your element id').click();");
    
    }
    }
    
    Summary
    • Waiting is having the automated task execution elapse a certain amount of time before continuing with the next step
    • Implicit waits are used to provide a default waiting time between each consecutive test step/command across the entire test script
    • Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed
    • Waits help the user to troubleshoot issues while re-directing to different web pages by refreshing the entire web page and re-loading the new web elements
    • Alert is a small message box which displays on-screen notification to give the user information or ask for permission to perform certain kind of operation
    • Selenium WebDriver provides switchto() method for switching between windows and frames

    Copyright 1999- Ducat Creative, All rights reserved.