Wednesday, June 26, 2024

Explicit Wait in Selenium

 

Explicit Wait:

Explicit Wait in Selenium

Definition: Explicit wait in Selenium allows you to define a specific condition to be met before proceeding further in the code. It is more flexible than implicit wait as it allows waiting for specific conditions for a defined amount of time.

Characteristics:

  • It is applied to a specific element, unlike implicit wait which is global.
  • It is used when you need to wait for a specific condition to occur before proceeding.

Defined Using Two Classes:

  1. WebDriverWait
  2. FluentWait

1. WebDriverWait

WebDriverWait is a subclass of FluentWait. It uses ExpectedConditions to wait until a certain condition is met.

 

 

package SynchronisationBasics;

 

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class ExplicitWaitUsingWebdriverWait {

 

            public static void main(String[] args) {

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver = new ChromeDriver();

 

                        driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

                        //***************************

                        //   takes some more time to display user name txt box,pwd element

                        // Create webdriverwait class obj

                        WebDriverWait  wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

                        // wait for title = OrangeHRM

                        wait.until(ExpectedConditions.titleIs("OrangeHRM"));

 

 

                        //                     // wait for title contains  OrangeHRM

 

 

                        //                     Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for title to contain "Orange123". Current title: "OrangeHRM" (tried for 10 second(s) with 500 milliseconds interval)

 

 

                        //  wait until  user name text box element  is visible -visibilityOf()- valid name

                   wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("username")));

                       

 

                        // wait untill ele is visible with invalid user name

//         wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("username123")));

 

                        //Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.name: username1214 (tried for 10 second(s) with 500 milliseconds interval)

 

 

 

                        //visibilityOfElementLocated()

                        // enter user name

                        driver.findElement(By.name("username")).sendKeys("Admin");

 

                        // Enter pwd - invalid locator  -- password123

                        driver.findElement(By.name("password")).sendKeys("admin123");

 

                        // give invalid locator

 

                        // ele is not found ,

 

 

                        // click login

                        driver.findElement(By.xpath("//button[contains(@class,'login')]")).click();

 

                        //We have to apply synchronisation, where ever it takes some time to display user name, admin link  or any ele --

 

                        // wait for "admin" link till visible ---  Expliti wait  and define condition

//         wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Admin']")));

            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Admin123']")));

 

                        // if ele found in page, with in 5 sec, remaining 5 Sec Selenium will not wait, it goes to next stmt

                        //  if ele is not found after waiting max time i.e 10 sec's, it throws "Timeout" Exception

 

                        // click admin link from left side menu

 

                        driver.findElement(By.xpath("//span[text()='Admin']")).click();

 

                        //HW  wait for user name textbox to be visible

 

 

                        // HW Enter some value in user anme

                        // Hint //  identify textbox name label name

 

 

 

            }

 

}

 

******************************************

            25-May-2024

******************************************

 

Revise:

------

 

                        driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");    

                        //    wait for so and so title contains-OrangeHRM

           

                        // after waiting max time out,   Webdrivewait throws  'TimeoutException"   but not nosuchelemntException

 

////    wait for so and so title is -OrangeHRM

                                   

                        ExpectedConditions.titleIs(null);

                        ExpectedConditions.titleContains("");

                       

//                     ExpectedConditions.visibilityOfElementLocated(By);// Prefer

//                     ExpectedConditions.visibilityOfAllElementsLocatedBy(By)

//                     ExpectedConditions.visibilityOf(webEle);

                       

//                     ExpectedConditions.invisibilityOfElementLocated(by);

//                     ExpectedConditions.invisibilityOf(ele);

                       

//                     ExpectedConditions.alertIsPresent();

//                     ExpectedConditions.elementToBeClickable(By);

//                     ExpectedConditions.elementToBeClickable(ele);

           

 

//                     ExpectedConditions.attributeContains(by , "attr name", "attr val");

                        ExpectedConditions.textToBePresentInElementValue(by , "text");

//                     ExpectedConditions.textToBePresentInElement(ele, text)  

                       

 

Refer :

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

           

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

 

2. FluentWait :

 

    predefined class in Selenium

-  can be used to define explicit wait

2. FluentWait

FluentWait is a more generic form of WebDriverWait. It allows you to define the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Characteristics:

  • You can set the polling interval.
  • You can ignore specific types of exceptions while waiting, such as NoSuchElementException.

 

 

package SynchronisationBasics;

 

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.NoSuchElementException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.FluentWait;

 

public class ExplicitWitUsingFluentWait {

 

            public static void main(String[] args) {

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver = new ChromeDriver();

 

                        driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

 

                        //************************************

                        //             wait for so and so title is = ORangge HRM

                        // create obj for FluentWait - class

 

                       

                        //   or

                        FluentWait<WebDriver> fwait = new FluentWait<WebDriver>(driver);

                        //  time

                       

                        fwait.withTimeout(Duration.ofSeconds(20))

                        .pollingEvery(Duration.ofSeconds(5))

                        .ignoring(NoSuchElementException.class);

                       

//                     fwait.until(ExpectedConditions.titleIs("OrangeHRM"));

                       

                       

                        //  or

//                     FluentWait<WebDriver> fwait = new FluentWait<WebDriver>(driver);

//                     //  time

//                    

//                     fwait.withTimeout(Duration.ofSeconds(10))

//                     .pollingEvery(Duration.ofSeconds(5))

//                     .ignoring(NoSuchElementException.class)

//                     .until(ExpectedConditions.titleIs("OrangeHRM"));

                       

 

 

           

                        //

                        //   invalid title

//                     fwait.until(ExpectedConditions.titleIs("OrangeHRM123"));

//                     Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for title to contain "Orange1243". Current title: "OrangeHRM" (tried for 20 second(s) with 5000 milliseconds interval)

 

                        // polling time :frequency with which to check the condition

                        //   for every 5sec,  it checks condition is true / false

                        // MAx time out = 20 sec

                        //  if Max time out is over, Fluent wait -  throws 'TimeOut Exception'

 

                        //Waiting for title contains so and so values "Orange"

                        System.out.println("Waiting for title contains so and so values");

 

                       

                        //  taking some time to display "username" textbox            

                        // wait for user name ele to visible

                  fwait.until(ExpectedConditions.visibilityOfElementLocated(By.name("username")));

 

                        //invalid loc

 

 

                        // enter user name                

                        driver.findElement(By.name("username")).sendKeys("Admin");

 

                                                // Enter pwd

                        driver.findElement(By.name("password")).sendKeys("admin123");

 

                        // click login

                        driver.findElement(By.xpath("//button[contains(@class,'login')]")).click();

 

                        // wait for "admin" text to be visible

            fwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Admin']")));

                                               

 

                        // click admin link from left side menu

                        driver.findElement(By.xpath("//span[text()='Admin']")).click();

 

                                               

 

                        // Note :

                        //         When click link, submit, Save the form --  it takes some time to give response --  

                                                // it takes some time to go to next page

                        //  we have to define explicit wait    and Define condition

 

 

            }

 

}

 

                       

FAQ Difference  between Implicit wait andExplicitwait ?

 

Implicit                                                                                    Explicitwait

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

1.It is global timeout.we can define only once and is applicable for each findElement() and FindElements()

 

old version:    

              driver.manage().timeouts().implicitlywait(20,TimeUnit.seconds);

 

Selenim 4 versions: we can pass duration arg                      

//                     or  with 1 args

                        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));

 

We have to define Explicit wait for specific ele

WebDriverWait wait2 = new WebDriverWait(driver, 20); // pass only 20 seconds

   or

WebDriverWait wait2 = new WebDriverWait(driver, Duration.ofSeconds(10));

// we can pass Duration.ofSeconds(10)

//          Duration.ofMinutes(2)

//       Duration.ofHours(1)

                       

                        //  define condition

                        wait2.until(ExpectedConditions.visibilityOf(LastNameEle));

 ex:   wait for till user name ele is visible for max 20 sec

 

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

 

2. In Implicitwait, we do not specify the condition  

In Explicitwait, We specify the condition

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

3. after waiting for max time in implicit, it throws ‘NoSuchElement’Exception

after waiting for max time in explicit, it throws ‘Timeout’Exception

 

Feature

Implicit Wait

Explicit Wait

Definition

Global timeout for the entire WebDriver instance.

Wait for a specific condition to be true before proceeding.

Application

Applies globally to all findElement() and findElements() calls.

Applied to specific elements and conditions.

Condition Specification

Does not specify a condition explicitly.

Requires explicit specification of conditions using ExpectedConditions.

Exception Handling

Throws NoSuchElementException if element not found within specified time.

Throws TimeoutException if condition not met within specified time.

Syntax (Older Versions)

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

Not applicable (Explicit wait is not directly supported in older versions).

Syntax (Selenium 4+)

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));<br>wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

Duration Arguments

Uses TimeUnit.SECONDS, TimeUnit.MINUTES, etc.

Uses Duration.ofSeconds(), Duration.ofMinutes(), etc.

Scope

Global across all WebDriver operations.

Local to specific element and condition.

 

FAQ:What is parent class for WebdriverWait ?

FluentWait

 

public class WebDriverWait extends FluentWait<WebDriver>

 

2. Fluent Wait

FluentWait<WebDriver> wait=  new FluentWait<WebDriver>(driver);

                       

                           wait.withTimeout(Duration.ofSeconds(3))

                                                .pollingEvery(Duration.ofSeconds(3))

                                                .ignoring(NoAlertPresentException.class)

                                                .until(ExpectedConditions.alertIsPresent());

                       

-Usually we prefer using webdriverWait

 

FAQ:  Difference between WebdriverWait &  fluentWait ?in

1. WebdriverWait is predefined class in selenium

    FluentWait  - is predefined class in selenium

 

2. both can be used to achieve explicit wait

 

3. Webdriverwait - we specify  max time out and  expected condition

   Fluent wait-    max time out + Expected condition +  polling time +  ignore some exceptions

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

 

Wait (I) :  is predefined   interface in Selenium

             abstract Method only  --   some where  we have define/ implement

 

public class FluentWait<T> extends java.lang.Object implements Wait<T>

{

 

 

 

}

 

public interface Wait<F>

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

FAQ:  WAP  to use Explicit Wait   and Different  conditions?

 

       wait for till the "user name" ele is visible  for max 10 sec

            webdriverWait  wait   = new WebdriverWait(driver, 10);

 

            wait.until(Expectedconditions.visibilityOf(by.xpath("")));

           

HW      wait for till some title = ORangeHRM

 

HW      Wait for till title contains 'Orange' or 'HRM'

 

 HW     wait for till username ele is invisible

      

 

HW      wait for till aler popup window is  present

 

            wait for till "login" button is clickable ..

 

ExpectedConditions.elementToBeClickable(By);

 

 

FAQ :ExpectedConditions -  class or Interface ?

Ans . class

 

ExpectedCondition -Interface

 

Refer API:

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

 

pageLoadTimeout():

// set the time of 30 seconds for page to complete the loading

if your page does not load within 30 seconds, 'TimeOutException' will be thrown.

 

driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

driver.get("https://www.google.com/");

 

In the code above, if your page does not load within 30 seconds, 'TimeOutException' will be thrown.

 

code:

----

package SynchronisationBasics;

 

import java.time.Duration;

import java.util.concurrent.TimeUnit;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class PageLoadTimeOutBasics1 {

 

            public static void main(String[] args) {

                        //open chrome browser                    

                                                System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                                                WebDriver  driver = new ChromeDriver();

 

                                                // get("url ") - to open the url in chrome browser

                                                driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

                                                //

                                                // define page load time out --  similiar to impliciwait

                                                // it takes some time to load page                

                                                // set page load time out for 20 seconds

//                                             driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);//  not working properly

                                               

                                                //  deprecated

                                                // or

 

 

                                                //or Selenium 4

//                                             driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(20));//  not working properly

 

 

                                                //  less time - set pageLoadTimeout 1 sec or 0 sec

                                                driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(0));

                                                // Exception in thread "main" org.openqa.selenium.TimeoutException: timeout:

                                                // Timed out receiving message from renderer: 1.000

 

 

                                                // Enter 'Admin' in Username  text box        

                                                driver.findElement(By.name("username")).sendKeys("Admin");

                                   

 

 

            }

 

}

                       

 

Thread.sleep(long time in ms):

The Thread.sleep(long time) method in Java is used to pause the execution of the current thread for a specified amount of time

Description:

  • Purpose: Pause the execution of the current thread for a specified duration.
  • Argument: Requires a long value representing the time to sleep in milliseconds (time).
  • Exception: Throws InterruptedException if another thread interrupts the current thread while it is sleeping. This exception needs to be handled or declared in the method's signature.

Best Practices:

  • Avoid Overuse: Overuse of Thread.sleep() can lead to longer execution times and flaky tests.
  • Use Explicit Waits: Prefer WebDriverWait and ExpectedConditions to wait for specific conditions rather than using Thread.sleep().

 

 

package SynchronisationBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class sleepBasics {

 

            public static void main(String[] args) throws InterruptedException {

                        //open chrome browser                    

                                                System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                                                WebDriver  driver = new ChromeDriver();

 

                                                // get("url ") - to open the url in chrome browser

                                                driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

                                               

                                                //  wait for some time 8 sec

                                                Thread.sleep(8000);

                                               

                                                //  throws interrupted exception

                                                //  program execution temporarily stopped  for given time

                                                //  we must give time in milli seconds

                                                //  no condition is defined

                                                //   even if the ele is present or not present,it waits for given time 8 sec,

                                                //after 8 sec, it goes to next stmt, execute it...

 

                                                // Enter 'Admin' in Username  text box        

                                                driver.findElement(By.name("username")).sendKeys("Admin");

                                               

                                                // Enter pwd in pwd

                                                driver.findElement(By.name("password")).sendKeys("admin123");

 

                                                // Click Login button //button[@type='submit']

 

                                                driver.findElement(By.xpath("//button[contains(@class,'login')]")).click();

                                               

                                                Thread.sleep(5000);

                                               

                                                // click admin link from left side menu

                                                driver.findElement(By.xpath("//span[text()='Admin']")).click();

                                               

 

 

            }

 

}

 

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...