Selenium
Selenium
Selenium
4.What is selenium?
It is open-source Automation Test Suit for web bases applications across
different browsers (Chrome, Firefox etc) and different platforms (Windows,
Mac etc)
It supports multiple programming langue: Java, c#, python. etc
5.Components of Selenium
Selenium Suit
Selenium IDE, Selenium RC , Selenium WebDriver ,Selenium Grid
Selenium -2(Merged RC and WEB driver)
Selenium -3 (New and improved Version)
What is selenium IDE?
Selenium IDE stands for Integrated Development Environment.
It is simple and easy to use.
No prior programming knowledge is required.
It is used as prototyping tool.
Selenium WebDriver?
-It is a component of selenium suite.
-It is a java interface, implemented by browser classes.
-It is an API (Application Program Interface) mediator between browser and
client libraries.
Web Driver is the key interface against which tests are written, but there are
several implementations.
These include:
● HtmlUnit Driver
● Firefox Driver
● Internet Explorer Driver
● Chrome Driver
● Opera Driver
● iOS Driver
● Microsoft Edge
Interface webdriver
{
Void get(String URL);
Void findElement();
}
Class FirefoxDriver implements webdriver
{
Void get(String URL)
{
Code to open firefox browser
}
Void findElement()
{
}
}
Class ChromeDriver implements webdriver
{
Void get(String URL)
{
Cod to open chrome browser
}
Void findElement()
{
}
}
Steps to download Chromedriver.exe files
1. Navigate to website https://chromedriver.chromium.org/downloads
2. Check your chrome browser version
3. Based on your browser version click on link, example if you have 99
version of chrome browser then use same link of the version example then
download 99 version. Click on this 99 version
4. Click on the zip file based on your operating system. Example if you have
windows then click on Chromedriver_win32.zip file and save in your local
machine
5. You need to unzip the file and save
What is selenium Grid?
It allows test cases to run parallelly in
-Different machines
-Different platform
-Different browsers.
12.What is locators
-Identify Web Elements
-Locating strategies:
Basic Locating Strategies: By ID, By Name, By Class name, By Tag name, By
Link Text, By partial Link Text.
Customized Locating strategies: By CSS and By XPath
Web driver methods to find web element
-findElement();
-findElements();
Basic Locators:
By ID
By name
By class name
By tag name
By link text
By partial link text
Particle -1
1.Open web page
2.locate username by id
3.locate password by name
4.locate login button
5.Switch to product page(Using getWindowHandle)
Driver.switchTo().window(currentwindownHandle)
6.locate sauce labs bolt t-shart
7.Using partial linktext
By CSS selector : Cascading Style Sheets
HTML Tag,id,class ,attribute Syntex
combination
Tag and id (tag#id)
Tag and class (tag.value of class)
Tag and attribute (tag[attribute=value])
Tag,class and attribute (tag.valueofClass[attribute=value])
Sub-string (start with=,ends
with=$,contains=*),tag[attribute=substring]
Practical:
1.Launch chrome browser
2.Open swag lab web page
3.Locate username name -tag#id using css selector
4.. Locate password name - Tag and attribute(name=’password’)
5.Locate Login button using tag.value of class name
6.Swith to product page using getWindown handel
switchTo().window
7.click on add to cart – Tag,class and attribute.
14.What is XPath?
XPath is the language used for locating nodes in an XML document. As HTML
can be an implementation of XML (XHTML), Selenium users can leverage this
powerful language to target elements in their web applications.
XPath extends beyond the simple methods of locating by id or name attributes,
and opens up all sorts of new possibilities such as locating the second radio
button on the page.
Reasons for using XPath is when I don’t have a suitable id or name attribute for
the element I wish to locate. You can use XPath to either locate the element in
absolute or relative to an element that does not have an id or name attribute.
XPath locators can also be used to specify elements via attributes other than id
and name.
-XPath stands for XML path
-it is query language to locate nodes in XML document
-It gives complete address of web element.
How to get XPath of web Element?
1.Generate automatically using browser plugin
-Chrome Browser: SelectorsHub
-FireFox browser – Firepath,Chropath
2.Write XPath manually
Different ways and methods for writing XPath
1.Absolute XPath
2.Releative XPath
3.Single Attribute
3.Multiple Attribute
5.AND
6.OR
7.contaits()
8.starts_with()()
9.text()
10.position()
11.Last()
1.Absolute XPath:
- It starts with the root node.
-Starts with the forward slash (/) .
if x path is calculated from beginning of the root of HTML tag to locate then it
is known as absolute x path. ex: //Html/body/H1/input. Absolute XPaths
contain the location of all elements from the root (html) and as a result
chances to fail if slightest adjustments to the application.
Advantages :It identifies the element very fast.
Disadvantages: If anything goes wrong like some other tag added or removed
in between then this path will no longer works,
-Example
Webpage-https://www.saucedemo.com/
Web Element -username
/html[1]/body[1]/div[1]/div[1]/div[2]/div[1]/div[1]/form[1]/input[1]
2.Relative XPath:
-A relative XPath starts from the element to be located and not from the root
It starts with double forward slash // .
if x path is calculated with nearest unique value then it is known as relative x
path. ex: xpath=//@frames/id=submit. By finding a nearby element with an id
or name attribute (ideally a parent element) you can locate your target
element based on the relationship. This is much less likely to change and can
make your tests more robust.
Advantages: You don’t need to mention the long XPath, you can start from the
middle or in between.
Disadvantages: It will take more time in identifying the element as we specify
the partial path not (exact path)
Syntax:
XPath - //tagename[@attribute name=’attribute value’]
3.XPath -using single attribute
//<HTML tag>[@attribute_name=’attribute_value’]
Or
//*[@attribute_name=’attribute_value’]
9.XPath-Using text
Syntax:
//<HTML tag>[text=’text’]
OR
//*[ text=’text’]
10.XPath -using position()
//tag-name[@attrubute-type=’attribute-value’][position()=value]
You can use this if more than one child name having same name in parent
element.
11.XPath-using las()
//tag-name[@attrubute-type=’attribute-value’][last()]
//input[@type=’text’][last()]
selectByValue()
deselectByValue()
selectByIndex()
deselectByIndex()
deselectAll()
To check if the drop-down element IsMultiple()
allows multiple selections at a time
To get options from dropdown getOptions()
Program:
1.Launch browser.
2.Open Application
3.Used Select class
4.Select the values from drop-down using
selectByVisibleTest(),selectByValue(),selectByIndex() methods.
5.isMultiple :Check drop down is multiple or not using if else .
6.Print all the drop-down values .using getOptions() method. Using for each
loop.
18.Alert Popup
What is Alert in selenium
An alert in selenium is a small message box which appears on screen to given
the user some information of notification.
Types of Alerts:
-Simple Alert: Display information or waring.
-Conformation Alert – asks permission to do some type of operation.
-Prompt Alert: Prompt Alert asks some inputs from the user.
driver.switchTo().alert().accept(); //Click on ok button
driver.switchTo().alert().dismiss(); //Click on cancel button
driver.switchTo().alert().sendKeys(); //Enter text on popup
19.Web Table
What is Web Table
Web Table is web element used to tabular representation of the data .
Program:1
Print the value of second column.
Program:2
Print the all values from table.
Note: You can check the tooltip message using getAttribute(); method to
compare the actual tooltip and the expected tool tip message.
22.Synchronisation issue
What is synchronization issue
The process of matching test automation tool speed with speed of application
under rest is synchronization.
Whenever webdriver tries to perform operation on element not loaded in
application under test , in such case webdriver will throw exception
“NoSuchElementExpection” or “ElementNoVisibleExpection” .This happens
due to synchronization issue.
Synchronization in selenium webdriver
Thread. Sleep(ms): It is unconditional and it is method of java .
Implicit Wait
Uses to set the default waiting time throughout the program.
It is global wait (it’s applied for all web element in the script) and it’s not web
element specific.
Syntax :
driver.manage().TimeOuts().implicitlyWait(10,Timeunit.SECONDS);//Before
Selenium 4
driver. manage().timeouts().implicitlyWait(Duration.ofSeconds()10));//After
selenium 4
Explicit wait:
Used to set the waiting time for a particular instance only.
It’s web element specific.
We can mentation the condition for specific element.
Syntax:
/*Explicit wait for dropdown webelement*/
WebDriver wait = new WebDriverWait(driver,10);//Before Selenium 4
WebDriver wait = new WebDriverWait(driver,Duration.ofSeconds(10));//After
Selenium 4
Wait.until(ExpectedCondition.visibilityOfElementLocated(By.id(“dropdown”)));
Let us discuss a few of them at length:
#1) elementToBeClickable() – The expected condition waits for an element to
be clickable i.e. it should be present/displayed/visible on the screen as well as
enabled.
Sample Code
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(“//
div[contains(text(),’COMPOSE’)]”)));
#2) textToBePresentInElement() – The expected condition waits for an
element having a certain string pattern.
Sample Code
wait.until(ExpectedConditions.textToBePresentInElement(By.xpath(“//
div[@id= ‘forgotPass'”), “text to be found”));
#3) alertIsPresent()- The expected condition waits for an alert box to appear.
Sample Code
wai0t.until(ExpectedConditions.alertIsPresent()) !=null);
#4) titleIs() – The expected condition waits for a page with a specific title.
Sample Code
wait.until(ExpectedConditions.titleIs(“gmail”));
#5) frameToBeAvailableAndSwitchToIt() – The expected condition waits for a
frame to be available and then as soon as the frame is available, the control
switches to it automatically.
Sample Code
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id(“newfr
ame”)));
Fluent wait
Used to set the waiting time but it will deep checking for element present in
given interval of times ,As soon as abject found it continue of execution
of code.
Its same as explicitly wait.
//Before selenium 4
Wait<WebDriver> wait = new FluneWait<WebDriver>(driver)
.withTimeout(10,TimeUnit.SECONDS)
.pollingEvery(5,TimeUnit.SECONDS)
.ignoring(NOSuchElementExeception.class)
//After selenium 4
Wait<WebDriver> wait = new FluneWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofSeconds(5)
.ignoring(NOSuchElementExeception.class)
Usage of JavaScriptExecutro
1.To click on a Button.
2.TO Type Text in a Text Box
3.To generate Alert pop window.
4.To refresh browser window using javascript.
5.TO get the domain name.
6. To get the Title of our webpage.
7.To get the URL of webpage.
8.To get the height and width of webpage.
9.To navigate to a different page using Javascript.
10.To perform scroll on an application.
11.To zoom webpage.
12.To flash a web element.
try {
Thread.sleep(20);//20ms
} catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
}
27.AutoIT
What is AutoIT
It is window based automation tool. It can automate desktop application.
Use of AutoIT in selenium
Selenium if confined to automating browsers, so desktop windows are out of
scope. To automate window based operations such as file upload, download
etc
Tools Required for AutoIT
Finder-To identify properties of the element .
https://www.autoitscript.com/site/autoit/downloads/
28.WebDriverManager
What is WebDriverManager ?
Selenium WebDriver is an automation tool widely popular and is useful to run
test against multiple browserts like Google Chrome browser,Firefox
browser,Internet Explore, etc.
We need browser drivers to launch any of these above browser
WebDriverManager in selenium , is a class that allows users to automate the
handling of driver executables like chromedriver.exe, geckodriver.exe, etc
required by selenium WebDriver API.
-Automates the management of WebDriver binaries.
-Downloads the appropriate driver,binaries,if not already present,into the
local cache.
-Downloads the latest version of the browser binary, unless otherwise
specified .
-Eliminates the need to store driver binaries locally. We also need not maintain
various version of the binary driver files for different browsers.
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-
core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
2) Download log4j-api
https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api/
2.17.1
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
Log4j2.xml file
This is also a configuration file having all runtime configuration used by
log4j.
https://logging.apache.org/log4j/2.x/
package com.jbs.codestudio;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
Syntax:
After the launch the browser,
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);
HTMLUnit Diver:
HtmlUnitDriver is headless driver providing non-GUI implementation of
Selenium WevDriver. It is written in Java. This is inbuilt headless browser
if selenium WebDriver.
Download :
https://mvnrepository.com/artifact/org.seleniumhq.selenium/
htmlunit-driver/3.60.0
35.Extent Reports
What is extend report
Extend Reports is an open-source HTML reporting library useful for test
automation. Extend API can produce more interactive reports, a dashboard
view, graphical view, capture screenshots at every test step, and emailable
reports.
Extent Report Maven Dependency:
40.Properties File
What is Properties File
Properties File in Selenium is a plain notepad file that are used to store the
hard coded values (Eg. Browser Name, URL, user id, Password etc.) in
selenium.
Properties file store the values in Key-Value pair.
Key=Value
Example:
browser = chrome
File Extension of properties file is. Properties.
For Comments - ! or # are used.
2.To scroll down the web page by the visibility of the element
//js.executeScript("arguments[0].scrollIntoView();",element);
3.To scroll down the web page at the bottom of the page
js.executeScript("window.scrollTo(0,document.body.scrolling)");