Synchronisation:
Def: Synchronization in Selenium refers to the process of
ensuring that the Selenium WebDriver code runs in sync with the web
application. This is necessary because Selenium executes commands very quickly,
often faster than the web application can respond. If the application is slow
to load elements, Selenium might not find the elements and throw exceptions
like NoSuchElementException.
Selenium code is too fast in identifying the ele.
if ele is not found in web page, it throws NoSuchElement
Exception immediately.
But application response might be slow. apply synchronisation in
order to sync - Selenium code and Application
-We cannot control application response . but We can control the Selenium code.
- To get proper results or o/p, We have to apply Synchronisation
ex1: after entering
username, password, click login- it takes some time to display home page-verify
home page displayed
ex2: when we save data, it takes some time to display new page or
new title
ex3: save the page, it
takes some time to display new alert popup window
Code execution and
application need to be in sync to perform the operations.
If the application slows down for any reasons like network, heavy
load, etc
then the code keeps on
checking for the particular web element. If the code is not able to find that
element it fails, by throwing exceptions like NoSuchElement, ElementNotVisible,
etc.
-Implicitwait :
- Explicit wait
-pageLoadTimeout(30, TimeUnit.SECONDS)
-Thread.sleep()
Implicit Wait in Selenium
Definition:
Implicit wait in Selenium sets a global timeout for all the web elements on
the page.
If an element is not found immediately, WebDriver will wait for a specified
duration before throwing a NoSuchElementException.
It is a global wait, which means it is applicable to all the findElement() and findElements() calls throughout the
WebDriver instance.
- It can
be defined only once and remains active until the WebDriver instance is
closed or the timeout is changed.
QTP/UFT: Object
synchronisation time out : 20 sec
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 ImplicitWaitBasics1 {
public static
void main(String[] args) {
//open
chrome browser
System.setProperty("webdriver.chrome.driver",
".\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
//******************************************
//
Implicitwait :
// global time out - can define only once and
it is applicable to each findElement()
and FindElements()
// if ele is not found in page, selenium throws
NoSuchElement Exception immediately.
// wait for some time
// QTP/UFT: Object synchronisatio time out : 20 sec
// Code:
//
before throwing exception , Selenium checks that if there is an implicit wait
is defined or not
// if
it is defined, Selenium waits for given
max time out .
// if
ele is present in page with in given time out, it return address of ele and
perform actions on that element
// if the ele is not present on page after
waiting given Max time, it throws no
suchElemnt Exception
//
Define implicitwait()
// driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
//
Selnium 4 version
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
System.out.println("enter
user name");
//
enter user name
driver.findElement(By.name("username")).sendKeys("Admin");
// Exception
in thread "main" org.openqa.selenium.NoSuchElementException: no such
element: Unable to locate element: {"method":"css
selector","selector":"*[name='username']"}
System.out.println("enter
pwd");
//
Enter pwd - invalid locator --
password123
// driver.findElement(By.name("password123")).sendKeys("admin123");
//
ele is not found ,
driver.findElement(By.name("password")).sendKeys("admin123");
System.out.println("Implicit
is applicatble for findElements() also ");
//
check for findElements() by passing invalid name
// driver.findElements(By.name("password123"));
//
ele is not found , even findElements()
waits max given time out , once it
reaches max time out,
//it does not throw NoSuchElementException
//
click login
driver.findElement(By.xpath("//button[contains(@class,'login')]")).click();
//
click admin link from left side menu
driver.findElement(By.xpath("//span[text()='Admin']")).click();
System.out.println("ends
");
}
}
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:
- WebDriverWait
- 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 |
Applied to specific elements and conditions. |
|
Condition Specification |
Does not specify a condition explicitly. |
Requires explicit specification of conditions using |
|
Exception Handling |
Throws |
Throws |
|
Syntax (Older Versions) |
|
Not applicable (Explicit wait is not directly supported in
older versions). |
|
Syntax (Selenium 4+) |
|
|
|
Duration Arguments |
Uses |
Uses |
|
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
InterruptedExceptionif 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
WebDriverWaitandExpectedConditionsto wait for specific conditions rather than usingThread.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