0% found this document useful (0 votes)
11 views34 pages

Selenium WD

Uploaded by

Ashwin jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views34 pages

Selenium WD

Uploaded by

Ashwin jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Selenium Basics

Introduction to Selenium WebDriver


• Selenium WebDriver one of the most
key component of SELENIUM Releases.
• Most powerful automation tool on which
“Open Source Community” relies on.
• A powerful API that’s easy to explore
and understand, which help us to make
our tests easier to read and maintain.
WebDriver Methods

Method: A Java method is a collection of statements that are grouped


together to perform an operation.

Method Name: To access any method of any class, we need to create an object
of class and then all the public methods will appear for the object.
Parameter: It is an argument which is passed to a method as a parameter to
perform some operation. Every argument must passed with the same data type.
For e.g. get(String arg0) : void. This is asking for a String type argument.
Return Type: Method can returns a value or returning nothing (void). If
the void is mentioned after the method, it means the method is returning no
value. And if it is returning any value, then it must display the type of the value for
e.g. getTitle() : String.
Get Commands
Command Syntax Sample code Notes

driver.get("http://www.google.com"); This method Load a new web


//Or can be written as page in the current browser
String URL = "http://www.DemoQA.com"; window. Accepts String as a
driver.get(appUrl) get(String arg0) : void driver.get(URL) parameter and returns nothing.

driver.getTitle(); This method fetches the Title of


//Or can be used as the current page. Accepts nothing
String Title = driver.getTitle(); as a parameter and returns a
driver.getTitle() getTitle() : String String value.
This method fetches the string
representing the Current
URL which is opened in
driver.getCurrentUrl(); the browser. Accepts nothing
//Or can be written as as a parameter and returns a
driver.getCurrentTitle(); getCurrentUrl() : String String CurrentUrl = driver.getCurrentUrl(); String value.
This method returns the Source
driver.getPageSource(); Code of the page. Accepts
getPageSource() : //Or can be written as nothing as a parameter and
driver.getPageSource(); String String PageSource = driver.getPageSource() returns a String value.
This method Close only the
current window the WebDriver is
driver.close(); currently controlling. Accepts
nothing as a parameter and
close() : void driver.close(); returns nothing.
This method Closes all windows
opened by the WebDriver.
Accepts nothing as a parameter
driver.quit(); quit() : void driver.quit(); and returns nothing.
Browser Navigation Commands
• The navigate interface exposes the ability to move
backwards and forwards in the browser’s history.
command Syntax Sample code Notes

driver.navigate().to(app It does exactly the same thing as


Url); the driver.get(appUrl) method.
Where appUrl is the website
to(String arg0) : driver.navigate().to("http: address to load. It is best to use a
void //www.DemoQA.com"); fully qualified URL.

This method does the same


operation as clicking on
the Forward Button of any
driver.navigate().forwar driver.navigate().forward() browser. It neither accepts nor
d(); forward() : void ; returns anything.

This method does the same


operation as clicking on the Back
driver.navigate().back() Button of any browser. It neither
; back() : void driver.navigate().back(); accepts nor returns anything.
This method Refresh the current
driver.navigate().refresh driver.navigate().refresh() page. It neither accepts nor returns
(); refresh() : void ; anything.
Web Element Identification
• WebElement represents an HTML element. HTML documents
are made up by HTML elements. HTML elements are written
with a start tag, with an end tag, with the content in
between: <tagname>content </tagname>
• WebElement can be of any type, like it can be a Text, Link,
Radio Button, Drop Down, WebTable or any HTML element.
• The web driver command findElement locates and returns the
web element upon which required action can be performed.

So, to get the WebElement object write the below statement:


WebElement element = driver.findElement(By.id(“UserNa
me“));
• If you type element dot, Eclipse’s intellisence will populate
the complete list of actions just like the above image.
Web Element Commands
• The web element commands help to perform action on the
web element objects.
command Syntax Sample code Notes
If this element is a text entry element,
this will clear the value. This method
WebElement element = accepts nothing as a parameter and
driver.findElement(By.id("UserName")); returns nothing.
element.clear(); This method has no effect on other
//Or can be written as elements. Text entry elements are INPUT
element.clear(); clear( ) : void driver.findElement(By.id("UserName")).clear(); and TEXTAREA elements.
This simulate typing into an element,
which may set its value. This method
accepts CharSequence as a parameter
WebElement element = and returns nothing.
driver.findElement(By.id("UserName")); This method works fine with text entry
element.sendKeys("ToolsQA"); elements like INPUT and TEXTAREA
sendKeys(CharSequen //Or can be written as elements.
element.sendKeys(“t ce… keysToSend ) : driver.findElement(By.id("UserName")).sendKe
ext”); void ys("ToolsQA");
WebElement element = This simulates the clicking of any
driver.findElement(By.linkText("ToolsQA")); element. Accepts nothing as a
element.click(); parameter and returns nothing.
//Or can be written as Clicking is perhaps the most common
way of interacting with web elements
driver.findElement(By.linkText("ToolsQA")).click like check boxes, links, radio boxes and
element.click(); click( ) : void (); many more.
WebElement element =
driver.findElement(By.id("SubmitButton"));
element.submit(); This method works well/better than the
//Or can be written as click() if the current element is a form,
or an element within a form. This
driver.findElement(By.id("SubmitButton")).sub accepts nothing as a parameter and
element.submit(); submit( ) : void mit(); returns nothing.
This method will fetch the visible (i.e.
not hidden by CSS) innerText of the
element. This accepts nothing as a
parameter but returns a String value.
WebElement element = This returns an innerText of the element,
driver.findElement(By.xpath("anyLink")); including sub-elements, without any
element.getText() getText( ) : String String linkText = element.getText(); leading or trailing whitespace.
Web Element Commands
• The web element commands help to perform action on the
web element objects.
command Syntax Sample code Notes

WebElement element = This method gets the tag name of this


driver.findElement(By.id("SubmitButton")); element. This accepts nothing as a
String tagName = element.getTagName(); parameter and returns a String value.
//Or can be written as This does not return the value of the
String tagName = name attribute but return the tag for e.g.
driver.findElement(By.id("SubmitButton")).getT “input“ for the element <input
element.getTagName(); getTagName( ) : String agName(); name="foo"/>.

This method gets the value of the given


attribute of the element. This accepts
WebElement element = the String as a parameter and returns a
driver.findElement(By.id("SubmitButton")); String value.
String attValue = Attributes are Ids, Name, Class extra and
getAttribute(String element.getAttribute("id"); //This will return using this method you can get the value
element.getAttribute(); Name) : String "SubmitButton" of the attributes of any given element.
This method Fetch CSS property value of
the give element. This accepts nothing
as a parameter and returns a String
value.
Color values should be returned as rgba
strings, so, for example if the
“background-color” property is set as
“green” in the HTML source, the
returned value will be “rgba(0, 255, 0,
element.getCssValue(); getCssvalue( ) : String 1)”.
Web Element Commands
• The web element commands help to perform action on the
web element objects.
command Syntax Sample code Notes

WebElement element =
driver.findElement(By.id("SubmitButton"));
Dimension dimensions = element.getSize();
System.out.println(“Height :” +
dimensions.height + ”Width : "+
dimensions.width);
WebElement element = This method fetch the width and height
driver.findElement(By.id("SubmitButton")); of the rendered element. This accepts
Dimension dimensions = element.getSize(); nothing as a parameter but returns the
System.out.println(“Height :” + Dimension object.
dimensions.height + ”Width : "+ This returns the size of the element on
element.getSize(); getSize( ) : Dimension dimensions.width); the page.

This method locate the location of the


element on the page. This accepts
WebElement element = nothing as a parameter but returns the
driver.findElement(By.id("SubmitButton")); Point object.
Point point = element.getLocation(); This returns the Point object, from which
System.out.println("X cordinate : " + point.x + we can get X and Y coordinates of
element.getLocation(); getLocation( ) : Point "Y cordinate: " + point.y); specific element.
Validation commands
• There are some commands to check the visibility/state of a
web element before performing any operation on the same.
command Syntax Sample code Notes

WebElement element =
driver.findElement(By.id("UserName"));
boolean status = element.isDisplayed(); This method determines if an element is
//Or can be written as currently being displayed or not. This accepts
boolean staus = nothing as a parameter but returns boolean
driver.findElement(By.id("UserName")).isDisplaye value(true/false).
element.isDisplayed(); isDisplayed( ) : boolean d();

WebElement element =
driver.findElement(By.id("UserName"));
boolean status = element.isEnabled();
// Check that if the Text field is enabled, if yes
enter value This determines if the element currently is
if(status){ Enabled or not? This accepts nothing as a
element.sendKeys("ToolsQA"); parameter but returns boolean
element.isEnabled(); isEnabled( ) : boolean } value(true/false).

Determine whether or not this element is


selected or not. This accepts nothing as a
WebElement element = parameter but returns boolean
driver.findElement(By.id("Sex-Male")); value(true/false).
boolean status = element.isSelected(); This operation only applies to input elements
//Or can be written as such as Checkboxes, Select Options and Radio
boolean staus = driver.findElement(By.id("Sex- Buttons. This returns True if the element is
element.isSelected(); isSelected( ) : boolean Male")).isSelected(); currently selected or checked, false otherwise.
Find Element
• Find Element and Find Elements methods to locate
element on the web page.
• findElement() method accepts something as a
Parameter/Argument and which is By Object. By is the
mechanism used to locate elements within a document with
the help of locator value.

• The different locators this is used by “By” class is listed below


findElement(s)
The difference
between findElement() and findElements() method is the first
returns a WebElementobject otherwise it throws an exception
and the latter returns a List of WebElements, it can return an
empty list if no DOM elements match the query.
Eg:
List<WebElement> allOptions =
select.findElements(By.tagName("option")); for (WebElement
option : allOptions) { System.out.println(String.format("Value is:
%s", option.getAttribute("value"))); option.click(); }
By locator variations
Browser tools for Element Inspector
Firefox: Firebug add on. Right click on any element and select Inspect Element or F12
Chrome: Build in Page analyzing feature (right click –> Inspect Element / F12)
IE: Developers Tool (Tools –> Developers Tools/ F12)

Command Syntax Sample code Notes

This is the most efficient and preferred


WebElement element = way to locate an element, as most of
driver.findElement(By.id("submit")); the times IDs are unique. It takes a
// Action can be performed on Input parameter of String which is a Value of
driver.findElement(By. Button element ID attribute and it returns a BY object
id(“Element ID”)); id(String id) : By element.submit(); to findElement() method.

This is also an efficient way to locate an


element but again the problem is same
as with ID that UI developer make it
having non-unique names on a page or
WebElement element = auto-generating the names. It takes a
driver.findElement(By.name("firstname") parameter of String which is a Value of
); NAME attribute and it returns a BY
driver.findElement(By. // Action can be performed on Input Text object to findElement() method.
name(“Element name(String name) : element
NAME”)); By element.sendKeys("ToolsQA");
By locator variations..contd..
Command Syntax Sample code Notes
This finds elements based on the value of
the CLASS attribute. It takes a parameter of
String which is a Value of CLASS attribute
and it returns a BY object to findElement()
method.

Note: This method is a life saver. As said,


class can contain many elements, many
times when you end up with duplicate IDs
and Names, just go for the ClassName first
WebElement parentElement = and try to locate the element with ID. That
driver.findElement(By.className("button")); will work fine, as the selenium will look for
driver.findElement(By.cl WebElement childElement = the ID which is in the mentioned class.
assName(“Element className(String parentElement.findElement(By.id("submit"));
CLASSNAME”)); className) : By childElement.submit();
With this you can find elements by their
TAGNAMES. It takes a parameter of String
WebElement element = which is a Value of TAG attribute and it
driver.findElement(By.tagName("button")); returns a BY object to findElement()
// Action can be performed on Input Button method.
element Locating Element By Tag Name is not too
element.submit(); much popular because in most of cases, we
WebElement element = will have other alternatives of element
driver.findElement(By.tagName("button")); locators. But yes if there is not any
driver.findElement(By.ta // Action can be performed on Input Button alternative then you can use element’s
gName(“Element tagName(String element DOM Tag Name to locate that element in
TAGNAME”)); name) : By element.submit(); WebDriver.
By locator variations..contd..
Command Syntax Sample code Notes

With this you can find elements of “a”


WebElement element = tags(Link) with the link names. Use this
driver.findElement(By.linkText("Partial when you know link text used within an
Link Test")); anchor tag. It takes a parameter of
driver.findElement(By. element.clear(); String which is a Value of LINKTEXT
linkText(“Element linkText(String attribute and it returns a BY object to
LINKTEXT”)); linkText) : By findElement() method.
Partial Link Text is also same as Link
WebElement element = text, but in this we can locate element
driver.findElement(By. driver.findElement(By.partialLinkText("Pa by partial link text too. In that case we
partialLinkText(“Eleme partialLinkText(String rtial"); need to use By.partialLinkText at place
nt LINKTEXT”)); linkText) : By element.clear(); of By.linkText.

It is most popular and majorly used


locating element technique or the
easiest way to locate element in
driver.findElement(By. WebDriver. It takes a parameter of
xpath(“Element xpath(String String which is a XPATHEXPRESSION
XPATHEXPRESSION xpathexpression) : and it returns a BY object to
”)); By findElement() method.
Check box selection
• CheckBox & Radio Button Operations are easy to
perform and most of the times the simple ID
attributes work fine for both of these.
• Operations on a check box includes validation for their
selection/deselection and if they are already
checked/selected by default.
Selection
method Sample code Notes

WebElement radioBtn =
driver.findElement(By.id("toolsqa")); If ID is given for the Radio Button/CheckBox
and you just want to click on it irrespective of
By ID radioBtn.click(); it’s value, then the command will be like this:

List oRadioButton =
driver.findElements(By.name("toolsqa"));
boolean bValue = false;
bValue =
oRadioButton.get(0).isSelected();
if(bValue = true){ If your choice is based on the pre-selection of
oRadioButton.get(1).click(); the Radio Button/Check Box and you just
}else{ need to select the deselected Radio
oRadioButton.get(0).click(); Button/Check Box. With IsSelected
} statement, you can get to know that the
IsSelected element is selected or not.
DropDown & Multiple Select Operations

• A DropDown/Multi select element will have <Select> as tag name.


• To perform any action, the first task is to identify the element group. I
am saying it a group, as DropDown /Multiple Select is not a single
element.
• They always have a single name but they contains one or more than
one elements in them.
• It is just an ordinary operation like selecting any other type of
element on a webpage. You can choose it by ID, Name, Css &
Xpath etc.
• To perform any action on Select element it is required to
import ‘importorg.openqa.selenium.support.ui.Select' package
and to use it we need to create a new Select Object of class Select.
• Select is a class which is provided by Selenium to perform multiple
operations on DropDown object and Multiple Select object.
• The below package needs to be imported for using select class:
import org.openqa.selenium.support.ui.Select;
Select oSelect = new Select(select element));
Sample code :
Select oSelect = new Select(driver.findElement(By.id("Country")));
Select method options
Selection method Command Sample code Notes

It is very easy to choose or


select an option given under any
Select oSelect = new dropdowns and multiple selection
Select(driver.findElement(By.id( boxes with selectByVisibleText
"yy_date_8"))); method. It takes a parameter of
oSelect.selectByVisibleText("20 String which is one of the Value
selectByVisibleText(String oSelect.selectByVisibleTe 10"); of Select element and it returns
arg0) : void xt(“text”); nothing.

It is almost the same as


selectByVisibleText but the only
Select oSelect = new difference here is that we provide
Select(driver.findElement(By.id( the index number of the option
"yy_date_8"))); here rather the option text.It
takes a parameter of int which is
selectByIndex(int arg0) : oSelect.selectByIndex(int oSelect.selectByIndex(4); the index value of Select element
void ); and it returns nothing.
The only difference in this is that
it ask for the value of the option
rather the option text or index.
Note: The value of an option and
the text of the option may not be
Select oSelect = new always same and there can be a
Select(driver.findElement(By.id( possibility that the value is not
"yy_date_8"))); assigned to Select webelement. If
the value is given in the Select
selectByValue(String oSelect.selectByValue(“te oSelect.selectByValue("2014"); tag then only you can use the
arg0) : void xt”); selectByValue method.
Select method options..contd
Selection method Command Sample code Notes

This gets the all options belonging


to the Select tag. It takes no
parameter and returns
Select oSelect = new
Select(driver.findElement(By.id("yy_date_8 List<WebElements>.
"))); Sometimes you may like to count
List <WebElement> elementCount = the element in the dropdown and
getOptions( ) : oSelect.getOptions(); multiple select box, so that you can
List<WebElement> oSelect.getOptions(); System.out.println(elementCount.size()); use the loop on Select element.

Select oSelect = new


Select(driver.findElement(By.id("yy_date_8
")));
List <WebElement> elementCount =
oSelect.getOptions();
int iSize = elementCount.size();
for(int i =0; i>iSize ; i++){
String sValue = To get the Count of the total elements
elementCount.get(i).getText(); inside SELECT and to Print the text
System.out.println(sValue); value of every element present in the
Print } SELECT.

This tells whether the SELECT element


support multiple selecting options at
the same time or not. This accepts
nothing by returns boolean
value(true/false).
This is done by checking the value of
isMultiple oSelect.isMultiple(); the “multiple” attribute.
DeSelect Methods
• The way we select different values of DropDown & Multi Select,
the same way we can also deselect the values. But the only
challenge in these methods are they do not work
for DropDown and only work forMulti Select elements.
• In case you want to deselect any pre-selected option, that can
be done with either deselectAll(), deselectByIndex,
deselectByValue and deselectByVisibletext.

Syntax Command Notes

Clear all selected entries. This is only


valid when the SELECT supports
deselectAll( ) : void oSelect.deselectAll; multiple selections.

deselectByIndex(int arg0) : void oSelect.deselectByIndex; Deselect the option at the given index.

deselectByValue(String arg0) : Deselect all options that have a value


void oSelect.deselectByValue; matching the argument.

deselectByVisibleText(String arg0) Deselect all options that display text


: void oSelect.deselectByVisibleText matching the argument.
XPATH - variations
xpath Technique Notes

Absolute XPath starts with the root node


or a forward slash (/).
The advantage of using absolute is, it
/html/body/table/tbody/tr/td/table identifies the element very fast.
/tbody/tr[1]/td/div/table/tbody/tr/ Disadvantage here is, if any thing goes
td[2]/table/tbody/tr[6]/td/ wrong or some other tag added in
table[1]/tbody/tr[1]/td/table/ between, then this path will no longer
tbody/tr[1]/td/input Absolute xpath works.

A relative xpath is one where the path


starts from the node of your choise - it
doesn't need to start from the root node.

It starts with Double forward slash(//)


Advantage of using relative xpath is, you
don't need to mention the long xpath,
you can start from the middle or in
between.

Disadvantage here is, it will take more


time in identifying the element as we
specify the partial path not (exact path).

If there are multiple elements for the


//tr[6]/td/table[1]/tbody/tr[1]/td/ same path, it will select the first element
table/tbody/tr[1]/td/input Relative Xpath that is identified
Partial xpath with single
//input[@id,’username’] attribute
XPATH - variations
xpath Technique Notes

Partial xpath with contains By using 'contains' function in XPath, we can extract all
//input[contains(@id,’username’)] keyword the elements which matches a particular text value.

By using 'starts-with' function in XPath, we can extract


element that starts with description as specified
//input[starts-with(@id=’user’)] Using starts-with method attribute.

//input[@id=’’]/following::input[1]
//input[@id='email']/following::tr It will identify the immediate node which start after
Using Following node the current node.

The following-sibling axis selects those nodes that are


siblings of the context node (that
//select[@id='month']/following-sibling::* is, the context node and its sibling nodes share a
//select[@id='month']/following- parent node) and which occur later in
sibling::select/ Following Sibling Axes document order than the context node.

The preceding axis contains all nodes in the same


document as the context node that are before the
context node in document order.
//input[@id='pass']/preceding::tr Preceding Axes
Synchronization
It is a mechanism which involves more than one
components to work parallel with Each other.
Generally in Test Automation, we have two
components
1. Application Under Test
2. Test Automation Tool.
Both these components will have their own
speed. We should write our scripts in such a way
that both the components should move with
same and desired speed, so that we will not
encounter "Element Not Found" errors which will
consume time again in debugging.
Synchronization
Synchronization is categorized into two:
• Unconditional :
In this we just specify timeout value only. We will make the tool to wait
until certain amount of time and then proceed further.
Examples: Wait() and Thread.Sleep();
The main method should be written as below to use thread.sleep()

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

The main disadvantage for the above statements are, there is a


chance of unnecessary waiting time even though the application is
ready.

• Conditional:
We specify a condition along with timeout value, so that tool waits to
check for the condition and then come out if nothing happens.
Conditional wait is further classified into implicit and explicit wait.
Implicit wait
• An implicit wait is to tell WebDriver to poll the DOM for a certain
amount of time when trying to find an element or elements if they
are not immediately available.
• It is a mechanism which will be written once and applied for entire
session automatically. It should be applied immediately once we
initiate the Webdriver.
• It will work only for "FindElement" and "FindElements" statements.
• We need to include the below package :
import java.util.concurrent.TimeUnit;
• Syntax:

driver.manage.TimeOuts.implicitwait(6,Timeunit.SECONDS);
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“www.gmail.com”);
Explicit Wait:
• We need to define a wait statement for certain condition to be
satisfied until the specified timeout period. If the Webdriver
finds the element within the timeout period the code will get
executed.
• Explicit wait is mostly used when we need to Wait for a specific
content/attribute change after performing any action, like when
application gives AJAX call to system and get dynamic data and
render on UI.
• The two packages need to be included:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

/*Explicit wait for state dropdown field*/
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("st
atedropdown")));
Explicit Wait - variations
Command Sample code Notes
WebDriverWait wait = new
WebDriverWait(driver, waitTime); ExpectedConditions will return true
wait.until(ExpectedConditions.presenceOfEle once the element is found in the
isElementPresent: mentLocated(locator)); DOM.
Below is the syntax to check if the
element is present on the DOM of a
page and visible. Visibility means
WebDriverWait wait = new that the element is not just
WebDriverWait(driver, waitTime); displayed but also should also has a
wait.until(ExpectedConditions.elementToBeC height and width that is greater than
isElementClickable lickable(locator)); 0.
WebDriverWait wait = new
WebDriverWait(driver, waitTime);

wait..until(ExpectedConditions.visibilityOf(el check the element to be visible by


visibilityOf ement)); WebElement.

List<WebElement> linkElements =
driver.findelements(By.cssSelector('#linkhell
o'));
visibilityOfAllElemen
WebDriverWait wait = new
ts
WebDriverWait(driver, waitTime);
check all elements present on the
wait..until(ExpectedConditions.visibilityOfAll web page are visible. We need to
Elements(linkElements)); pass list of WebElements.
WebElement element =
driver.findElement(By.id("")); check if the element is enabled or
isElementEnabled element.isEnabled(); not.
WebElement element = check if the element is displayed or
driver.findElement(By.id("")); not. It returns false when the
isElementDisplayed element.isDisplayed(); element is not present in DOM.
Fluent Waits:
• Fluent waits are also called smart waits also. They are called smart primarily because
they don’t wait for the max time out, specified in the .withTimeout(5000,
TimeUnit.MILLISECONDS). Instead it waits for the time till the condition specified
in .until(YourCondition) method becomes true.

When the until method is called, following things happen in strictly this sequence
Step 1: In this step fluent wait captures the wait start time.
Step 2: Fluent wait checks the condition that is mentioned in the .until() method
Step 3: If the condition is not met, a thread sleep is applied with time out of the
value mentioned in the .pollingEvery(250, TimeUnit.MILLISECONDS) method call.
In the example above it is of 250 milliseconds.
Step 4: Once the thread sleep of step 3 expires, a check of start time is made
with the current time. If the difference between wait start time, as captured in
step 1, and the current time is less than time specified in .withTimeout(5000,
TimeUnit.MILLISECONDS) then step 2 is repeated.
This process keeps on happening till the time either the time out expires or the
condition comes out to be true.
Fluent Wait:
//Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
//Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)

//This is how we specify the condition to wait on.


//This is what we will explore more in this chapter
wait.until(ExpectedConditions.alertIsPresent());
Handling Alerts
• Alert is a pop up window that comes up on screen.
• There are many user actions that can result in an alert on screen. For
e.g. user clicked on a button that displayed a message or may be when
you entered a form, HTML page asked you for some extra information.
• Alerts are different from regular windows. The main difference is that
alerts are blocking in nature. They will not allow any action on the
underlying webpage if they are present.
• If an alert is present on the webpage and you try to access any of the
element in the underlying page you will get following exception:
UnhandledAlertException: Modal dialog present
• Selenium provides us with an interface called Alert. It is present in
the org.openqa.selenium.Alertpackage. Alert interface gives us
following methods to deal with the alert:
accept() To accept the alert
dismiss() To dismiss the alert
getText() To get the text of the alert
sendKeys() To write some text to the alert
Handling Alerts
• Alert is a pop up window that comes up on screen.
• There are many user actions that can result in an alert on screen. For
e.g. user clicked on a button that displayed a message or may be when
you entered a form, HTML page asked you for some extra information.
• Alerts are different from regular windows. The main difference is that
alerts are blocking in nature. They will not allow any action on the
underlying webpage if they are present.
• If an alert is present on the webpage and you try to access any of the
element in the underlying page you will get following exception:
UnhandledAlertException: Modal dialog present
• Selenium provides us with an interface called Alert. It is present in
the org.openqa.selenium.Alertpackage. Alert interface gives us
following methods to deal with the alert:
accept() To accept the alert
dismiss() To dismiss the alert
getText() To get the text of the alert
sendKeys() To write some text to the alert
Switch Window
commands
• Some web applications have many frames or multiple windows.
• 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.
Command Sample Code Notes
Return a string of
String handle= alphanumeric window
getWindowHandle() driver.getWindowHandle(); handle

Set<String> handle= Return a set of window


driver.getWindowHandles(); handle
Handling iframes
• iFrame is a HTML document embedded inside an HTML document.
iFrame is defined by an <iframe></iframe> tag in HTML. With this tag
you can identify an iFrame while inspecting the HTML tree.
• In order to switch to iframes, we need to use switchto() command.
driver.switchTo().frame()
• Switching to a frame can be done in 3 ways:
switchTo.frame(int frameNumber): Pass the frame index and
driver will switch to that frame.
//Switch by Index
driver.switchTo().frame(0);
switchTo.frame(string frameNameOrId): Pass the frame
element Name or ID and driver will switch to that frame.
//Switch by frame name
driver.switchTo().frame("iframe1");
switchTo.frame(WebElement frameElement): Pass the frame
web element and driver will switch to that frame.
//Switch by frame ID
driver.switchTo().frame("IF1");
Handling iframes
• Switching back to Main page from Frame
• In order to switch between one frame and another, you need to
switch back to main page and then switch to the other frame.

WebElement iframeElement = driver.findElement(By.id("IF1"));


//now use the switch command
driver.switchTo().frame(0);
//Do all the required tasks in the frame 0
//Switch back to the main window
driver.switchTo().defaultContent();
driver.switchTo().frame(0);
• To find total number of iFrames on a webpage:
List<WebElement> iframeElements =
driver.findElements(By.tagName("iframe"));
System.out.println("The total number of iframes are " +
iframeElements.size());
Handling Drag And Drop/Mouse events in Selenium Webdriver

In Webdriver, handling keyboard events and mouse events (including


actions such as Drag and Drop or clicking multiple elements With Control
key) are done using the advanced user interactions API.

• It contains Actions and Action classes which are needed when


performing these events.
• In order to perform action events, we need to use
org.openqa.selenium.interactions.Actions class.

You might also like