Selenium automates the browsers. Selenium is an open source testing Framework for web based applications. It works based on Selenium IDE which reduces efforts to work on scripts.
Selenium provides interface to write test cases in a variety of languages like c#, Java, PHP, Python, Scala,etc and then we can run these test cases against any supported web browser. Selenium new demanded version is named as selenium webdriver.
Selenium provides interface to write test cases in a variety of languages like c#, Java, PHP, Python, Scala,etc and then we can run these test cases against any supported web browser. Selenium new demanded version is named as selenium webdriver.
SELENIUM WEBDRIVER: If you want to create robust, browser-based regression automation suites and tests, scale and distribute scripts across many environments, then you want to use Selenium WebDriver, a collection of language specific bindings to drive a browser - the way it is meant to be driven.
Selenium:
- Open source
- Used for functional testing
- wide range of supported language
- works on different browsers, operating support
Selenium Architecture:
Selenium java ( Archive files) ===> Eclipse (Compiler) ==> Selenium Webdriver ( A program that drive the browser) ==> Browser
Pre-Requites:
- JDK - “JDK creates abstract layer upon the hardware and install JVM (Java Virtual Machine) that runs Java”
- Eclipse (compiler)- Compiler is a translator – It will translate your Java Code into Byte Code
Installation process:
Installation Guide contains following :
a. Java Development Kit (JDK).
b. Compiler – Eclipse.
c. Firefox, Firebug & Firepath.
d. Selenium JAR (Java Archive) Files.
Selenium: Installation Guide (Getting your System & Tools ready)
On Your Marks!!! Get Set Go…
1. Before you Start… (Operating System): What: Check “System Type” Why: Required Tools Compatibility How: Several Ways.
Step 1 - Click on Windows “Menu” Icon (Windows 7)
Step 2 – Select “Control Panel”
Step 3 – Select “System & Security”
Step 4 – Select “System”
2. Setting Up Environment (Middle Layer)
What: Download & Install JDK (Java Development Kit)
“JDK creates abstract layer upon the hardware and install JVM (Java Virtual Machine) that runs Java”
Why: So we can run Eclipse (Tool) & Java (Coding Language) on system under use.
How: Follow the instructions below: Step 1 - Go to the link
https://www.oracle.com/java/technologies/javase-jdk14-downloads.html
Step 2 – Read & Accept License Agreement in “Java SE Development Kit 7u79” table:
Step 3 – Select the relevant download option according to your System Type.
Step 4 – Follow the on screen instruction and complete the installation.
3. Download Eclipse (Compiler)
(Compiler is a translator – It will translate your Java Code into Byte Code)
What: Eclipse
Why: Need a tool for coding (Automation Scripts) How: Follow the instructions below:
Step 1 - Go to the link https://www.eclipse.org/downloads/
Page 1 of 2
Selenium - Installation Guide
Step 2 – Select the relevant Operating system bit in "Eclipse IDE for java Developers"
Step 3 – Once Downloaded Extract files from the ZIP folder. (Remember the path i.e. Default folder path)
Step 4 – Create a Desktop Shortcut - Open the Default Folder in “Windows Explorer” and follow the following:
• Double Click on the Downloaded Folder (eclipse-java-mars-1win32-x86_64)
• Double Click on “eclipse” Folder.
• Right Click on “eclipse icon – Type “Application”)
• Send to Select “Desktop (Create Shortcut)
Download FireFox Browser & Addons: Install Firefox, Firebug and Firepath Extensions:
What: Firefox, Firebug & Firepath. Why: Let it be secret at this stage ;-) How: Follow the instructions below:
Step 1 – To Install “Mozilla Firefox Browser” Go to the link https://www.mozilla.org/en-GB/firefox/desktop/ and follow the instructions.
Step 2 – To Install “Firebug Addon” Go to the link https://getfirebug.com/downloads/) and follow the instructions. Step 3 – To Install “Firepath Addon” Go to the link https://addons.mozilla.org/en-GB/firefox/addon/firepath/ and follow the instructions.
Well Done You Are doing GREAT!!!
4. Download Selenium Jar Files. (IT IS NOT A SOFTWARE) What: Selenium Jar “Java Archive” files. Why: Let it be secret at this stage ;-) How: Follow the instructions below:
Step 1 – Go to the link http://docs.seleniumhq.org/download/. Step 2 – Under Heading “Selenium Client & Webdriver Language Bindings” Click on “Download” for Java.
Step 3 – Go to Download Folder double Click on “Selenium Java ZIP Archive” Extract All FilesSh
shortcut of eclipse:
shift + contrl + O = Import all origanize / To import above classes automatically, you can select “Source” > “Organize Imports”
SELENIUM WEBDRIVER: If you want to create robust, browser-based regression automation suites and tests, scale and distribute scripts across many environments, then you want to use Selenium WebDriver, a collection of language specific bindings to drive a browser - the way it is meant to be driven.
Invoking Browser:
Selenium ---> Framework -----> Classes --> functions
class --> container within selenium which contain multiple functions.
functions ---> set of instruction
Browser --> open / lunch it, load the required URL, perform certain action, close. Class - function
This is a Eclipse Project format:
Fig: Invoke Browser:
Selenium Assertion - verify actual result and expected result
This following selenium automation script has following features:
01 Invoke the web browser & load URL.
02 Manage Browser Window- Maximize windows,
03 Delete Cookies
04 Capture Browser Title.
05 Capture Opened URL.
06 Capture Page Source.
07 Assertion: verify expected and actual result
08 Quit Browser Window.
package com.automation.eng.AutomationProject;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
@Test
public class InvokeBrowser {
public WebDriver driver;
public void WebDriverManagerTest()
{
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create driver object for Chrome
driver = new ChromeDriver();
// Maximize the browser window
driver.manage().window().maximize();
//Delete all cookies
driver.manage().deleteAllCookies();
//Navigate to a URL
driver.get("https://javaqaeng.blogspot.com/");
//Assert title
String actualTitle = driver.getTitle();
String URL = driver.getCurrentUrl();
String SourceCode = driver.getPageSource();
//Get title of page - printing title of page
System.out.println("My page title is :" + actualTitle);
//Get URL
System.out.println("My URL is: " + URL);
// Getting source code
//System.out.println("Source code is below: " + SourceCode);
String expectedTitle =
"FREE Professional Java Developer, Automation Engineer, Business Analyst Training";
//Assert my title
assertEquals(expectedTitle,actualTitle);
//Another way of assertion - it does not need to all title for assertion
assertTrue(driver.getTitle().contains("FREE Professional Java Developer"));
// OR Verify expected page title and actual page title is same
Assert.assertTrue(actualTitle.equalsIgnoreCase(expectedTitle
),"FREE Professional Java Developer, Automation Engineer, Business Analyst Training");
//OR you can use if/else - please do not confuse - it is optional
if(driver.getTitle().contains("FREE Professional Java Developer"))
//Pass
System.out.println("Page title contains \"FREE Professional Java Developer\" ");
else
//Fail
System.out.println("Page title doesn't contains \"FREE Professional Java Developer\" ");
//close the browser
driver.quit();
}
}
/*
* My page title is :FREE Professional Java Developer, Automation Engineer, Business Analyst Training
My URL is: https://javaqaeng.blogspot.com/
Page title contains "FREE Professional Java Developer"
PASSED: WebDriverManagerTest
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
*/
Java:
- Its a popular programming language developed by James Gosling in 1995
- intended to "write once run everywhere" (WORA)
- Compiled to Bytecode which can run on every computer architecture
Variables: It is a small containers or boxes that create to store our data temporarily in computer memory.
package com.automation.eng.AutomationProject;
import java.util.Scanner;
/**
* Hello world!
*
*/
public class CalculatorApp
{
public static void main( String[] args )
{
int number1;
int number2;
int result;
Scanner sc = new Scanner(System.in);
System.out.println( "Enter a First number: " );
number1 = sc.nextInt();
System.out.println("The number Input by the user is: " + number1);
System.out.println( "Enter a Second number: " );
number2 = sc.nextInt();
System.out.println("The number Input by the user is: " + number2);
result = number1 + number2;
System.out.println("Sum of Number is : " + result);
result = number1 - number2;
System.out.println("Substraction of Number is : " + result);
}
}
/*
* Enter a First number:
78
The number Input by the user is: 78
Enter a Second number:
40
The number Input by the user is: 40
Sum of Number is : 118
Substraction of Number is : 38
*/
* /
*/
Section : Locator Techniques:
(i) Locate Web elements with xpath.
(ii) Locate Web Elements With customized xpath.
How to Identify Dynamic Web Elements?
- Absolute Path method
- Use Relative XPath using contains or starts with text
- Identify by index - driver.findElements(By.xpath(//*[contains(@id, ‘submit’).get(0).click();Here get(0) is used to get the first web element with matching XPath.
- Use Multiple attributes to locate an element ( and, or)
Xapath:
XPath is defined as XML path. It is a syntax or language for finding any element on the web page using XML path expression.
- // : Select current node.
- Tagname: Tagname of the particular node.
- @: Select attribute.
- Attribute: Attribute name of the node.
- Value: Value of the attribute.
XPath is a path written using html tags(or XML tags) and their attributes to reach to a particular node (or web element) in an HTML page or XML page.
Types of Xpath:
- Relative xpath - It starts with the double forward slash (//), which means it can search the element anywhere at the web page.Basic Syntax: //htmlTagname[@attribute=’value’]
Figure: This tag with the name input ,(it has some characteristics - it has id,type,class. we called this characteristics as a attributes), the tag with name input, it has a attribute id and the value of this attributes, which is id is equals to postComentSubmit.
The tag with name an input, has an attribute called type and this attributes has value "button".
- Absolute xpath - The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node. Basic Syntax: html/body/table/tbody/tr[2]/td/input
Methods in Xpaths:
Contains():
Contains is a method used when the value of any attribute changes dynamically. It can search an element with partial information.
Example: To search a button xPath used can be: //input[contains(@type=’submit’)]
Example 2: Xpath of a below displayed web element using contains method can be written like:
//input[contains(@name=’email’)] or //input[contains(@name=’ema’)]
Both above examples will work because contains uses partial matching.
Example 3: Using another method text() as an argument to the contains() method in XPath.
//a[contains(text(), ‘Mobile & Accessories’)]
Above xpath will search for the links which has a text Mobile & Accessories as the linktext.
Starts-with()–
This method can be used when we are searching for web elements matching the start of the text of the attributes passed. The text() method can also be used which will match the starting of the text.
Syntax: For above example, xpath can be written using starts-with as
//a[starts-with(text(),’Flight’)]
Text() –
This method is used when we are searching for elements matching the exact text.
//a[text()=’Mobile & Accessories’]
Operators in xpath:
AND and OR is two operators available in xpath.
AND operator, when applied to multiple attributes, identifies a web element only when all the attributes are pointing to that element.
Syntax: //input[@type=’text’ and @name=’uid’]
This xpath will identify an input web element which is of type text and name as uid.
OR operator, when applied to multiple attributes, defines a web element only when any one of the attributes points to that element:
Syntax: //input[@type=’text’ or @name=’uid’]
This xpath will identify an input web element which is either of type text or name is “uid.”
AXES in Selenium WebDriver:
Axis in xpath points the xpath processor to the direction in which it should navigate in the hierarchy of the html nodes.
Basic Syntax:
//html_tag[@attribute=’value’]//axes::html_tag
Frequently used Axes in XPath:
- Ancestor – contains ancestor of the context node.
- Child – includes the child of the context node.
- Following – select the elements which follow after the context node.
- Preceding – choose the elements which precede before the context node.
- Following-Sibling – choose the sibling coming after the context node.
- Preceding-Sibling – choose the sibling coming before the context node.
- Parent – contains the parent of the context node.
Section :Automating Web UI - Check Boxes and Radio Buttons:
01 Handling Checkboxes.
02 Handling Radio Buttons via customized xpath.
A form consists of various elements like text box, email field, password field, text area, radio buttons, checkbox, dropdowns, links, etc.
- Input Box – It consists of either a text field or an email field or a password field. The action which we can perform in a text box are:
- Passing Text – method used is sendKeys(“String”);
WebElement oUsername;
oUsername = oBrowser.findElement(By.id("u_0_1"));
//To clear the text
oUsername.clear();
//To enter string value in a text field
oUsername.sendKeys("Merisa");
- Clearing Text – method used is clear();
- Radio Button – Radio button allows you to select one option out of many. The Action which can be performed on a radio button is click().
//To select a radio button - click() method is used
Driver.findElement(By.id("u_0_f")).click();
- Checkbox – Checkbox allows multiple selections as well. A checkbox can be toggled ON/OFF by click() method.
//To toogle a checkbox - click method is used
Driver.findElement(By.xpath("//input[@type='checkbox']")).click();
- Links – Links in html are hyperlinks, clicking on a link will navigate you to another page or document.
- Dropdown – Dropdown is a web element which gives us many options to select from. Dropdown in HTML is represented by Select tag, and its elements are represented by option tag.
- Buttons – There are used to submit a form. Actions that can be performed on a button are click() and submit().
//To submit a button either click() or submit method is used
Driver.findElement(By.id("gh-btn")).click();
//or
Driver.findElement(By.id("gh-btn")).submit();
Waits in Selenium Web Driver
The wait functions are essential when it comes to executing Selenium tests. They help to observe and troubleshoot issues that may occur due to variation in time lag.
In automation testing, wait commands direct the test execution to pause for a certain length of time before moving onto the next step. This enables WebDriver to check if one or more web elements are present/visible/enriched/clickable, etc.
In Selenium WebDriver, to sync up scripts there are four types of wait:
- Page Load Timeout
- Implicit Wait
- Explicit Wait
- Fluent Wait
Page Load Timeout:
This is the maximum time selenium waits for a page to load successfully on a browser. If the page takes more than this time, it will throw a Timeout Exception.
driver.manage().timeouts().pageLoadTimeout(90, TimeUnit.SECONDS);
Here Selenium WebDriver instance will wait a maximum of 90 seconds for a webpage to load. If it is loaded before the specified wait time, the execution will move to the next line of the script. If it doesn’t get loaded in 90 seconds it will throw the Timeout Exception.
Implicit Wait
It the maximum time (Threshold value), selenium code waits to interact with that Web Element, before throwing “Element not found
exception”.
Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs
To add implicit waits in test scripts, import the following package.
import java.util.concurrent.TimeUnit;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Add the above code into the test script. It sets an implicit wait after the instantiation of WebDriver instance variable.
Explicit Wait
This wait can be considered as conditional wait and is applied to a particular Web Element with a condition.
public void waitTillElementVisible(){
WebDriverWait wait = new WebDriverWait(Driver, 90);
wait.until(ExpectedConditions.visibilityOfElementsLocatedBy(By.xpath("//input[@type='text']")));
}
Here, the reference variable is named <wait> for the <WebDriverWait> class. It is instantiated using the WebDriver instance.
To use Explicit Wait in test scripts, import the following packages into the script.
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
In order to declare explicit wait, one has to use “ExpectedConditions”. The following Expected Conditions can be used in Explicit Wait.
- alertIsPresent()
- elementSelectionStateToBe()
- elementToBeClickable()
- elementToBeSelected()
- frameToBeAvaliableAndSwitchToIt()
- invisibilityOfTheElementLocated()
- invisibilityOfElementWithText()
- presenceOfAllElementsLocatedBy()
- presenceOfElementLocated()
- textToBePresentInElement()
- textToBePresentInElementLocated()
- textToBePresentInElementValue()
- titleIs()
- titleContains()
- visibilityOf()
- visibilityOfAllElements()
- visibilityOfAllElementsLocatedBy()
- visibilityOfElementLocated()
Fluent Wait
In Fluent wait, a maximum time is defined to wait for a condition and along with that polling time is also defined. Polling time is the frequency with which the condition is checked. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
To put it simply, Fluent Wait looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.
public static void fluentWait(WebDriver driver, int timeout, int pollingTime, By by){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(timeout))
.pollingEvery(Duration.ofSeconds(pollingTime))
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
In this code, the maximum time to wait is passed as timeout, polling time (a frequency with which condition is checked again) is passed as “pollingTime” and we are waiting for a condition to get true i.e. visibility of Element located by.
package com.automation.eng.AutomationProject;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
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;
import io.github.bonigarcia.wdm.WebDriverManager;
public class WaitTime {
private WebDriver driver;
private String baseUrl;
@BeforeMethod
public void setUp() throws Exception {
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create driver object for Chrome
driver = new ChromeDriver();
// Maximize the browser window
driver.manage().window().maximize();
//Delete all cookies
driver.manage().deleteAllCookies();
//Navigate to a URL
baseUrl = "https://javaqaeng.blogspot.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testUnited() throws Exception {
driver.get(baseUrl);
//Assert title
String actualTitle = driver.getTitle();
String URL = driver.getCurrentUrl();
//Get title of page - printing title of page
System.out.println("My page title is :" + actualTitle);
//Get URL
System.out.println("My URL is: " + URL);
String expectedTitle =
"FREE Professional Java Developer, Automation Engineer, Business Analyst Training";
//Assert my title
assertEquals(expectedTitle,actualTitle);
//Another way of assertion - it does not need to all title for assertion
assertTrue(driver.getTitle().contains("FREE Professional Java Developer"));
// OR Verify expected page title and actual page title is same
Assert.assertTrue(actualTitle.equalsIgnoreCase(expectedTitle
),"FREE Professional Java Developer, Automation Engineer, Business Analyst Training");
//OR you can use if/else - please do not confuse - it is optional
if(driver.getTitle().contains("FREE Professional Java Developer"))
//Pass
System.out.println("Page title contains \"FREE Professional Java Developer\" ");
else
//Fail
System.out.println("Page title doesn't contains \"FREE Professional Java Developer\" ");
// explicit wait - to wait for the compose button to be click-able
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='PopularPosts1']/h2")));
// print heading when it is visible
System.out.println("My bottom title is: " + driver.findElement(By.xpath("//div[@id='PopularPosts1']/h2")).getText());
}
@AfterMethod
public void tearDown() throws Exception {
// closes all the browser windows opened by web driver
driver.quit();
}
}
/*/
*
* My page title is :FREE Professional Java Developer, Automation Engineer, Business Analyst Training
My URL is: https://javaqaeng.blogspot.com/
Page title contains "FREE Professional Java Developer"
My bottom title is: Popular Posts
PASSED: testUnited
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
*/
Reference:
No comments:
Post a Comment