Selenium

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

1.What is automation Testing?

Automation testing is the process of doing testing without any manual


intervention. We automate manual test cases using any of the automation
tools with any of one programming language.

2.What do we need to Automate? Or Advantages of Automation.


• To Save time
• To save money
• Reusable (we can run same test cases any number of times like regression
testing)
• Error-prone human behaviour.

3.Disadvantages of Automation Testing?


 Test Automation requires lot of effort at initial stage.
 100% Test automation is impractical.
 All types of Testing not possible (Ex: Usability).
 Debugging issues.
 Tools may have their own defects.
 Programming Knowledge is required.

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.

6.Advantages of selenium Web Driver


-It is open-source tool.
-It supports multiple browsers -firefox,chrome ,opera etc.
-It supports multiple platforms -winds ,linux,Mac o sets.
-It’s supports multiple languages-java,python,rubu c# etc

7.Disadvantages of selenium Web Driver


-It supports only web bases application and doesn’t support window bases
application.
-It does not provide facility for data driven testing.
-It does not have reporting feature.
Third party Tool/LIBRARY to overcome disadvantages.
-Windows Operation – AutoIT
-Data driven testing -Apachi POI
-Reporting -Extend Report
8.Selenium Web Driver Architecture
Selenium 3.0 Architecture:

Selenium Web Driver Installation

9.Selenium Web Driver – First Test Case


Write a script for login application and verify Title of the application.

10.How to launch browser in selenium web driver


Web Web Driver commands
Browser
System.setProperty(“KEY”,”VALUE”) WebDriver driver=new
BrowserClass();
Mozilla System.setProperty(“Webdriver.gecko.driver”,”PathOfGeckodriver.ex
Firefox e”) WebDriver driver=new FirefoxDriver();
Google System.setProperty(“Webdriver.chrome.driver”,”PathOfGeckodriver.
Chrome exe”) WebDriver driver=new ChromeDriver();
Internet System.setProperty(“Webdriver.ie.driver”,”PathOfGeckodriver.exe”)
Explore WebDriver driver=new InternetExploreDriver();
11.Web driver commands to open web page
get method navigate() method
driver.get(“URL”) driver.navigate.to(“URL”)
Web driver will wait until the page It is only responsible for redirecting
has fully loaded before test or script. the page and then returning
immediately
It cannot track the history of the It tracks the browser history and can
browser perform back and forth in the
browser. Page refresh option is also
available in navigation() method .
driver.navigae().refresh;
driver.naviage.forwared();
driver.navigate().back();

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’]

4.XPath-using multiple attribute:


//<HTML tag>[@attribute_name1=’attribute_value1’]
[@attribute_name2=’attribute_value2’]
Or
//*[@attribute_name1=’attribute_value1’]
//*[@attribute_name2=’attribute_value2’]
Note:* after double slash is to match any tag with the desired text.
Piratical-Login Script for any application using xpath
5.XPath-Using And Expression
//<HTML tag>[@attribute_name1=’attribute_value1’ and
@attribute_name2=’attribute_value2’]
Or
//*[@attribute_name1=’attribute_value1’ and
@attribute_name2=’attribute_value2’]
Note: Both conditions should be true
6.XPath-Using OR Expression
//<HTML tag>[@attribute_name1=’attribute_value1’ or
@attribute_name2=’attribute_value2’]
Or
//*[@attribute_name1=’attribute_value1’ or
@attribute_name2=’attribute_value2’]
Note: At least one condition should be true
Piratical-Using condition AND or OR XPath
1.Login application
2.Swith to product page-getWindowHandle
3.Click on product details.

7.XPath -Using contains ()


Contains() method helps in locating the UI element using partial text.
Syntax:
//<HTML tag>[contains(@attribute_name,’attribute_value1’)]
OR
//*[ contains(@attribute_name,’attribute_value1’)]
Note:’*’ after double slash is to match any tag with the desired text.

8.XPath -Using starts-with


Syntax:
//<HTML tag>[starts-with (@attribute_name,’attribute_value1’)]
OR
//*[ starts-with(@attribute_name,’attribute_value1’)]
Example:
-Id= “message12”
-Id= “message345”
-Id= “message8769”
Practical: Login application.

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()]

15.Handling of Dropdown using select class:


-Select class is used to interact with Dropdown web elements.
-Commonly used command for dropdown interactions.
ACTIONS WEB DRIVER METHODS
To select/deselect values from selectByVisibleText()
dropdown deselectByVisibleText()

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.

16.Mouse Operations (Actions Class)


How to perform Mouse Operation
In Selenium webdriver, Actions class is used to handling keyword and mouse
operation.
Below are some of the methods to perform keyword and mouse operations.
ACTIONS ACTIONS CLASS METHODS
Perform right click operation on the contextClick();
mouse
Perform double click on the element. doubleClick();
Drags the element from one point dragAndDrop();
and drops to another.
Move the mouse pointer to the moveToElement();
centre of the element.
Perform long click on the mouse clickAndHold();
without releasing it.

17.How to Upload file


We can upload the file using below method and class.
1.SendKeys () method: We can use sendKeys() method to upload file for
windows bases Alerts/Pop-up.
Note: You can use sendKyes() method if type=’file’ in html properties.
2.Robot class: Robot class using keypress and key release method.
Program: Robot class
1.Applicion Open.
2.Create WebElement.
3.Perform Actions – Using Actions class
4.Creat Robot class
5.copy file to clip board -Using StringSelect class
StringSelection ss = new StringSelection(“path of the file”);
Toolkit.getDefaultToolKit(). getSystemSclipboard().setContents(ss,null);
6.Perform control +v action to past file using
keypress(keyEvent.VK_CONTROL)
keypress(keyEvent.VK_V);
keyRelease(keyEvent.VK_CONTROL)
keyReleasekeyEvent.VK_V);
//Enter Key
keyPress(keyEvent.VK_ENTER);
keyReleasekeyEvent.VK_ENTER);

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.

20.How to Handel Tool Tip


A Tooltip is a text that appears when a mouse hovers over an abject/web
element on a web page.
The object /web element can be a link, an image, a button, a text area etc.
The tooltip text often gives more information about the object/web element
on which the user hovers over the mouse cursor.
Example:

Note: You can check the tooltip message using getAttribute(); method to
compare the actual tooltip and the expected tool tip message.

21.How To Open New Tab Or Window


In Selenium Version 4 , you can open new window & tab using “newWindow”
command.
Example:
WebDriver driver = new ChromeDriver();
//Open New Window
Driver.switchTo().newWindow(WindowType.WINDOW);
//Open New Tab
driver.switchTo().newWindow(WindowType.TAB)
Program :
1.Launch chrome browser.
2.Open URL
3.Open New Tab
4.get window handles of open windows

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)

23. Window Authentication Popup


We can handle authentication popup with Selenium. To do this, we have to
pass the user credentials within the URL. We shall have to add the username
and password to the URL.
Syntax:
https://username:password@URL
https://admin:admin@the-internet.herokuapp.com/basic_auth
Here, the admin is the username and password.
URL − http://the-internet.herokuapp.com/basic_auth
24.Handling of Frame & Iframe
What is Frame & Iframe. Difference between Frame and Iframe.
How to identify the iframe
How do switch over the elements in iframes using Web Driver commands.
How to handle dynamic iframes using Selenium WebDriver.
Concept of Nested (Frames inside Frames)
Methods Provided by Selenium for handling iFrames.
Frame and Iframe:
Frame is a HTML tag that is used to divide the web page into various
frames/windows. Each window can load a separate HTML document.
In HTML,<frame>tag denotes a frame , and all the frames are present in a
<frame>
Tag.
Iframe as <iframe> is also a tag used in HTML but it specifies an inline frame
which means it is used to embed some other document or content from other
sources/external sources within the current HTML document.
How to switch to iframe:
1.By id or by name
2.By webelement
3.By index
Syntax : driver.switchTo().frame()
For switching the main page from frame, we can use defaultContent(); method
.
NOTE: We cannot switching one frame to another frame without main page.
How to find total iframes on web page
How to handle nested iframes()frames inside frames) in selenium WebDriver
Methods Provided by Selenium for Handling iFrames:
1.switchTo.frame(int frameNumber)
2. switchTo.frame(string frameNumber)
3. switchTo.frame(WebElement frameNumber)
4. switchTo.defaultContent()
5. switchTo.parentFrame

25.How to capture screenshot


Capture screenshot in selenium Webdriver.
Capture screenshot of Full page(Visible part of the page)
Capture screenshot of Section of a web page.
Capture screenshot of a web element of a web page.
Steps to capture screenshot
To capture screenshot, we will use method “getScreenShotAs()” of special
interface called “TakeScreenShot”
Steps1) Convert web driver object to TakeScreenshot
TakeScreenshot scrShot=((TakesScreenshot)webdriver);
Step2)Call getScreenshotAs method to create image file
File SrcFile =scrShot.getScreenshotAs(OutputTupe.FILE);
Step3)Copy file to Desired Location by using library “Apache Commons IO-
FileUtils”.
26.Java Script Executor
What is javaScriptExecutor ?
JavaScriptExecutor is an interface that helps to execute JavaScript through
selenium Webdriver.
Syntax:
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript(Script,Arguments);
Script – This is the JavaScript that need to execute
Arguments – It is the arguments to the script, it’s optional.
Returns – Could be anything from Boolean , Long, String , List ,
WebElement, or null.

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.

1.To Type Text in a Text Box


js.executeScript("document.getElementById('enter id').valu='test to be
enter';");
2.To Click on a button
js.executeScript("arguments[0].click();",element);
3.To Refresh the browser window/page
js.executeScript("history.go(0)");
4.To get the Domain Name
String domain =js.executeScript("return document.domain;").toString();
System.out.println("Domain Name :"+domain);

5.To Draw border around element


js.executeScript("arguments[0].style.border= '3px solid red'", element);
6.To get the Title of Our Webpage
String title =js.executeScript("return document.title;").toString();
System.out.println("Title Name :"+title);
7.To get the URL of Our Webpage
String url =js.executeScript("return document.URL;").toString();
System.out.println("URL Name :"+url);
8.To zoom page
js.executeScript("document.body.style.zoom='50%'");
9.To get the Height and Width of a web page.
String height =js.executeScript("return window.innerHeight;").toString();
System.out.println("Height :"+height);
String width =js.executeScript("return window.innerWidth;").toString();
System.out.println("Height :"+width);
10.To perform scroll on an application
//scroll vertically page up
js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
//Scroll vertically page up
js.executeScript("window.scrollBy(0,-document.body.scrollHeight)");
11.To generate Alert pop window in selenium web driver
js.executeScript("alert('Alert messge.');");
12.To navigate to a different page using java script
js.executeScript("window.location = 'URL'");
js.executeScript("window.location='https://www.google.com'");
13.To Flash webelement
//flash
String bgcolor = element.getCssValue("backgroundColor");
for(int i=0;i<50;i++) {
js.executeScript("arguments[0].style.backgroundColor='#000000'",element);
try {
Thread.sleep(20);//20ms
} catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
js.executeScript("arguments[0].style.backgroundColor= '"+bgcolor
+"'",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/

Editor – To create script


https://www.autoitscript.com/site/autoit-script-editor/downloads/
Steps :
Invoke AutoIT
Invoke AutoIT script editor
1.Write script to upload file
2.compile script and create exe
3.use exe in selenium code

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.

29.Log4j2 -Logging Framework


What is Logging:
Logging means some way to indicate the state of the system at runtime. The
log message have to provide the required information to understand what the
application does internally during runtime.
What is Log4j
Log4j logging framework which is written in java. It is an open-source logging
API for java.
Configuration:
1) Download log4j-core
https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-
core/2.17.1

<!-- 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>

3) Log4j2.properties file or Log4j2.xml file


Paste these log4j2.properties or log4j2.xml in project home directory.

log4j2.properties file is a log4j configuration file.


Which stores entire runtime configuration used by log4j.
Location: src/main/resource

Log4j2.xml file
This is also a configuration file having all runtime configuration used by
log4j.

4) Import log4j package


Import org.apache.logging.log4j.*;
5) Create object of Logger
Logger log = LogManger.getLogger(“ClassName”);

https://logging.apache.org/log4j/2.x/

30.Page Object Model


What is Page Object Model:
Page Object Model (POM) is design pattern, popularly used in test automation
that creates Object Repository for web UI elements.
Under POM:
Each web page is application.
There is separate class for each web page to identify web elements of that web
page and methods which perform operations on those Web Elements.
POM Implementation
Without Page Factory
-By().method
-findElement()
With Page Factory
-@FindBy annotation
-PageFactory.initElement()
This initElements method will create all WebElements.

31.How to Encode Password/Sensitive Data


What is Encoding /Encryption:
Encryption is the process of converting plain text data into an unreadable
format in order to protect unauthorized access.
To secure our passwords/sensitive data we can use Base64 encoding scheme in
Selenium WebDriver.
We will import this Base64 class in our script to decode password/Sensitive
data.

32.How to Fill A form In A One Statement

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;

public class LoginForm {


@Test
public void hrmLogin() throws Throwable {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/
auth/login");
driver.manage().window().maximize();
Thread.sleep(3000);
Actions actions = new Actions(driver);
Action seriesOfAction = actions
.moveToElement(driver.findElement(By.xpath
("//input[@placeholder='Username']")))
.click()
.sendKeys("Admin",Keys.TAB)
.sendKeys("admin123",Keys.ENTER).build();
seriesOfAction.perform();
}}

33.How to Read Data from Excel files (Data Driver Testing)


What is Data Driven Testing:
Data-driven testing is a test automation framework which stores test data in a
table or spread spreadsheet format (eg.Excle File)
Using Java classes and Apache POI library we can manipulate (read/write) excel
Files (both XLS and XLSX file format) in selenium webdriver.
1. Create a maven java project.
2. Navigate to Maven Central Repository.
3. Search for “Apache POI”.
You need to copy below dependencies:
a.poi
b.poi-ooxml
4. Click on central tab and copy latest dependencies.
5.Paste above dependencies in pom.xml of you maven project and save it.
Note: As soon as you save it, Maven will build workspace with Apache POI
dependencies.
Excel -> Workbook ->Sheet->Rows->Cell
34.Headless Browser Testing:
What is A headless Browser
Headless Browser, Means a Web Browser without User Interface. To elaborate,
Headless Browsers are those which actually access the web page , but the
GUI/Screen is hidden from the user.
Advantages of Headless Browser:
1. Headless Browsers are used when the machine has no GUI.
2. These can be used in a case where there is no need to view anything and
our purpose is just to ensure that all tests are getting executed
successfully line by line.
3. When there is a need for executing parallel tests , UI bases browsers
consume a lot of memory and/or resources. Hence, here Headless
browser is preferred to use.
4. When compared to Real Browsers, Headless Browsers are faster. So,
these are chosen for faster execution.
Disadvantages of Headless Browser :
1. As headless browser are very fast, due to its faster page loading ability,
sometimes it is difficult to debug the issues.
2. When tests are to be performed in front of user, where the user con
interact with the team, referring the GUI and discuss where ever
changes or corrections are required. In such case, Headless Browsers
cannot be used and Real browser testing are done as it has GUI.
3. As Headless Browsers don’t represent GUI, it is troublesome to report
errors with the help of screenshots.

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

//Launch HtmlUnitDirver browser


HtmlUnitDirver driver = new HtmlUnitDirver();

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:

<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->


<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.9</version>
</dependency>

36.How to Get Source URL of Image

37.How to Automate Date Picker -Pending for work


38.How to Handel Cookies
What is HTTP cookie
A HTTP cookie is comprised of information about the user and their
preferences. It is small piece of the data sent from web application and stored
in web browser, while the user is browsing that website.
Methods To Query and Interact with Cookies:
1. driver.manager().getCookies(); //Return The List of all Cookies.
2. driver.manager().getCookieNamed(arg0)//Return specific cookie
according to name.
3. driver.manager().addCookie(arg0)//Crate and add the cookie
create object for creating Cookie.
4. drivrer.manager().deleteCookie(arg0);//Delete specific cookie.
5. driver.manager().deleteCookieNamed(arg0);//Delete specific cookie
according Name.
6. driver.manager().deleteAllCookies();//Delete all cookies.

39.Extend Report Using TestNG Lister


Listener
TestNG listeners are the piece of the code that listens to the events occurring
in the TestNG.
By using TestNG listeners ‘ITestListner’ or ‘TestListenerAdapter’ we can change
the default behaviour of TestNG and write our won implementation when a
Test fails or Skips etc.
We extend TestListnerAdapter which intern implements ITestListner interface
with empty methods. So again, we don’t have to overridden other methods
form the ITestListner interface which we may not needed.

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.

41.How to scroll web page


-To scroll down the web page by pixel.
-To scroll down the web page by the visibility of the element.
-To scroll down the web page at the bottom of the page.
-Horizontal scroll on the web page.
To scroll using selenium, you can use JavaScriptExecutor interface that helps to
execute JavaScript methods through Selenium Webdriver.
Syntax:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeAsyncScript(script,Arguments);

1.To scroll down the web page by pixel


//js.executeAsyncScript("window.scrollBy(s-pixels.y-pixels)");
js.executeScript("window.scrollBy(0,500)");//scroll vertically down by 500
pixels

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)");

4.Horizontal scroll on the web page.


js.executeScript("arguments[0].scrollIntoView();",element);
42.How to find broken links/dead links on web page-Pending
-Broken links are links or URLs that are not reachable. They may be down or
not functioning due to some error .
-The user entered an improper/misspell URL
-The destination web page is donw,moved,or no longer exists.
-With activated firewall settings , also the browser cannot access the
destination web page at times.
Program:
1.Launch browser.
2.Maximise page
3.Add Implicitlywait
4.Open Url
5.Find hyperlinks : list of webelemnts using findElements() method using tag
name.
6.Using foreach loop : print the url using href attribute and stored in variable.
7.Uisng URL class

43.How to count no. of radio buttons on web page.


-Find common locator for all radio buttons.
-Capture list of radio button using FindElements() method.
-Get count of elements in a list using size() method to obtain total no. of radio
button on web page.
Program:
1.Launch chrome browser
2.Maximixe browser
3.Open URL
4.List of webEelemets using webElements() method .
5.Print total no. of radio button in radio button list using size() method.
6.close browser
44.How to count and print hyperlink on webpage.
Program:
1.Lauch chrome browser
2.Launch web page https://www.calculators.net
3.Using findElements and xpath=tagename(“a”)
4.Print:Total links on webpage using size() method.
5.pring using for or for each loop using getText() method.
5.close browser

45.How to click on image links in selenium webdriver


Locate the image link on web page
-Image links are the links in web pages represented by an image which when
clicked navigates to a different window or page.
-we cannot use the By.linkText() and By.partialLinkText() methods because
image links basically have no links texts at all .
-In this case , we can use By.cssSelector or By.xpath to locate the image link.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy