SELENIUM NOTES(after the course align this notes with src code for
revesion) and consolidate the Quiz.
Assignements:
1. Checkboxes exercise
2. UI(Dropdowns,EditBoxes,Error Valdiation)
3. Synchronization with Explicit wait – Assignment
4. Window Handling
5. Frames
6. writing dynamic tests with out hardcoding values[After lec97]
FEATURES:
open Source
exclusively for Web Based applications.
multiple browsers
Multiple Platforms
multiple languages
Difference between Selenium and WebDriver?
Selenium WebDriver Architectue Simplified:
After you trigger the Test, complete Selenium code (Client) which we
have written will be converted to Json format
Generated Json is sent to Browser Driver (Server) through http Protocol.
Note: Each browser contains a separate browser driver
.Browser drivers communicate with its respective browser and executes
the commands by interpreting Json which It received on the browser.
Browser Driver receives responses back from the browser and it sends
Json response back to Client.
WebDriver is an Interface which provides Set of Browser Automation
methods with empty bodies (Abstract methods)
Classes like ChromeDriver, FirefoxDriver, MicrosoftEdgeDriver ,
SafariDriver etc implement the WebDriver Interface
and provide their own implementation to the WebDriver methods
We need to create the object of the class to access the methods present
in the class.
ChromeDriver driver = new ChromeDriver ();
driver object here has access to all the methods of Chrome driver
WebDriver driver = new ChromeDriver ();
driver object here has access to the methods of Chrome driver which
are defined in web Driver Interface
Selenium Web Driver Locators
As part of Automation, Selenium Performs actions (such as
click, typing) on the Page HTML Elements.
The Locators are the way to identify an HTML element on a web
page. Locators will tell us where the html element is present…
Selenium WebDriver uses any of the below locators to identify
the element on the page and performs the Action
ID
Xpath no mapping, need to construct from given html code via syntax
CSS Selector no mapping, need to construct from given html code via
syntax
name
Class Name
Tag Name
Link Text : <a href="#">Forgot your password?</a>
driver.findElement(By.linkText("Forgot your password?")).click();
Partial Link Text
Input -> tag name
Red-> attribute
Green-> attribute associated value.
<input type="text" placeholder="Username" id=
“inputUsername” value=" ">
ID LOCATOR:
driver.findElement(By.id("inputUsername")).sendKeys("Aditya Gupta");
<input type="password" placeholder="Password"
name="inputPassword" value="">
NAME LOCATOR:
driver.findElement(By.name("inputPassword")).sendKeys("Aditya@12");
<button class="submit signInBtn" type="submit">Sign
In</button>
CLASSNAME LOCATOR:
driver.findElement(By.className("signInBtn")).click();
<p class="error">* Incorrect username or password </p>
CSS SELECTOR LOCATOR:s
therefore css selector for above code is p.error VImp
Therefore to print error message…
Before printing, make sure you sycnchronize…
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
//synchronization
now print error…
System.out.println(driver.findElement(By.cssSelector("p.error")).getT
ext());
For forgot password: html syntax
<a href="#">Forgot your password?</a>
a = anchor tag name , href= attribute , Forgot your
password = LINK TEXT therefore will use LINK text
Locator:
driver.findElement(By.linkText("Forgot your password?")).click();
XPATH LOCATORS: <input type="text" placeholder="Name">
driver.findElement(By.xpath("//
input[@placeholder='Name']")).sendKeys("Aditya Gupta");
<input type="text" placeholder="Email">
Css Selector-
Class name -> tagname.classname -> Button.signInBtn ->
p.error or .error(used when single class name is there)
$('p.error') to be used under inspect under console to check
multiple css selectors are there or not(UNIQUE CSS)… Done
when we aren’t allow to download selectors hub browser
plugin
Id -> tagname#id -> input#inputUsername
Tagname[attribute=’value’] --- >>> used if html don’t have
classname or id or name
EXAMPLE :
<input type="text" placeholder="Username” value=" ">
Input [placeholder= ’ Username’ ] This is css selector if we
don’t have id,name,classname
Tagname[attribute=’value’]:nth-child(index). - Child items
Parenttagname childtagname
input[type*='pass'] – CSS
tagname
Absolute(/) and Relative(//) XPATH.:
Absolute XPath: Begins from the root of the HTML document and
specifies the complete path to the element. It's not as flexible and
can break if the page structure changes. Relative XPath: Starts
from a specific element and navigates through the DOM hierarchy
to locate the desired element
Xpath –
//Tagname[@attribute=’value’]
<input type="text" placeholder="Username" id=
“inputUsername” value=" ">
Therefore == >>> //input[@placeholder=’ Username’’]
<input type="text" placeholder="Name">
//input[@placeholder=’ Name’]
//Tagname[@attribute=’value’][index] //using xpath when
same attributes with multiple index
//parentTagname/childTagname writing xpaths w/o
attributes using tagnames
//button[contains(@class,'submit')]. – Regular expression
(Only in xpath and not in css selector)Sibling traverse:
//header/div/button[1]/following-sibling::button[1]
By.xpath("//header/div/button[1]/following-sibling::button[1]")
//sibling traverse (relative xpath)
By.xpath("//header/div/button[1]/parent::div/button[2]")) //child element
to parent element traverse
//header/div/button[1]/parent::div
For finding text using Xpath…w/o using LinkText
<button class="logout-btn">Log Out</button>
driver.findElement(By.xpath("//button[text()='Log Out']")).click();
// driver.findElement(By.xpath("//*[text()='Log Out']")).click();
//line 68 be written as...
Undertstanding Ui Components Automation
Handling Static Dropdowns
Handling Dynamic Dropdowns: loaded when users select the
particular options/action/cities(inc of Flight booking ex)
options are loaded based on users actions…
Handling Checkboxes
Handling radio buttons
Handling Text Buttons
Handling Alerts-Java Popups
Selenium Webdriver Form Methods
Example of static dropdowns:
<select name="ctl00$mainContent$DropDownListCurrency" id="ctl00_mainContent_DropDownListCurrency"
class="valid">
<option value="">Select</option>
<option value="INR">INR</option>
<option value="AED">AED</option>
<option value="USD">USD</option>
</select>
If tag name is select-> then its Static Dropdown
WebDriver d = new ChromeDriver();
d.get("https://rahulshettyacademy.com/dropdownsPractise/");
//Dropdown with Select Tag
WebElement staticDropdown =
d.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Select dropdown = new Select(staticDropdown);
dropdown.selectByIndex(3);
dropdown.selectByVisibleText("AED");
dropdown.selectByValue("INR");
Dynamic Dropdown:
// a[@value='BLR'] --> appears 2 times dynamically(@origin and
@destination) once origin is selected
// Therefore==>(//a[@value='BLR'])[2] USED
d.findElement(By.xpath("(//a[@value='BLR'])[2]")).click();
the single forward slash (/) selects only the immediate child
elements, while the double forward slash (//) selects all
descendants of the current node, regardless of their level.
PARENT-CHILD Relationship XPATH locator VIMPPPPP=>identify
objects uniquely
d.findElement(By.xpath("//
div[@id='glsctl00_mainContent_ddl_destinationStation1_CTNR']
//a[@value='BLR']")).click();
AutoSuggestive Dropdowns: Options come Based on i/p It will auto suggest:
d.findElement(By.id("autosuggest")).sendKeys("ind");
Thread.sleep(3000);
List<WebElement> options = d.findElements(By.cssSelector("li[class='ui-menu-item']
a"));
for(WebElement option : options) {
//System.out.println(option.getText());
if(option.getText().equalsIgnoreCase("India")) {
option.click();
break;
//EXTRA SRC CODEREFER LATER
/*
WebDriver driver =new ChromeDriver();
driver.get("https://www.makemytrip.com/"); //URL in the browser
WebElement source=driver.findElement(By.id("hp-widget__sfrom"));
source.clear();
source.sendKeys("MUM");
Thread.sleep(2000);
source.sendKeys(Keys.ENTER);
WebElement destination=driver.findElement(By.id("hp-widget__sTo"));
destination.clear();
destination.sendKeys("DEL");
Thread.sleep(2000);
destination.sendKeys(Keys.ARROW_DOWN);
destination.sendKeys(Keys.ENTER);
*/
Handling checkboxes and getting the size of them:
//input[contains(@id,'SeniorCitizenDiscount')] Xpath: When Not to write whole sentence of
element
input[id*='SeniorCitizenDiscount'] Css Selector: When Not to write whole sentence of element
Importance Of Assertions: to put validations of our test
java.lang.AssertionError: expected [false] but found [true]
Assert.assertFalse(d.findElement(By.cssSelector("input[id*='SeniorCitizenDi
scount']")).isSelected());
Assert.assertFalse(d.findElement(By.cssSelector("input[id*='SeniorCitizenDi
scount']")).isSelected());
Assert.assertEquals(d.findElement(By.id("divpaxinfo")).getText(), "5
Adult");
java.lang.AssertionError: expected [5 Adult] but found [4 Adult]
//Handling Calendar:
Many a time a test fails to click on an element or enter text in a field as
the element is
disabled or exists in the DOM, but is not displayed on the page; this will
result in an error
being thrown and the test resulting in failures. For building reliable
tests that can run
unattended, a robust exception and error handling is needed in the test
flow.
We can handle these problems by checking the state of elements. The
WebElement class
provides the following methods to check the state of an element:
Method Purpose
isEnabled() This method checks if an element is enabled. Returns true if
enabled,
else false for disabled.
isSelected() This method checks if element is selected (radio button,
checkbox, and
so on). It returns true if selected, else false for deselected
isDisplayed() This method checks if element is displayed.
In this recipe, we will use some of these methods to check the status and
handle
possible errors.
Locators for class type element:
<a class="ui-state-default ui-state-highlight ui-state-active"
href="#">7</a>
XPATH: //a[@class='ui-state-default ui-state-highlight ui-state-hover']
CSS: .ui-state-default.ui-state-highlight.ui-state-hover (Refer basics)
//Validating if UI Element: checking enable disable via opacity by:finding
element and getting the attribute
if(d.findElement(By.id("Div1")).getAttribute("style").contains("1")) {
System.out.println("Is enabled !");
Assert.assertTrue(true //VIMP
}
else {System.out.println("Is not enabled !");
Assert.assertFalse(false); //VIMP
}
//Example of diff Locator method to choose locators:
d.findElement(By.cssSelector("#ctl00_mainContent_btn_FindFlights"));using
css to find ID type element (Refer Basics)
d.findElement(By.cssSelector("input[value='Search']")).click();
d.findElement(By.xpath("//input[@value='Search']")).click();
d.findElement(By.name("ctl00$mainContent$btn_FindFlights"));
d.findElement(By.id("ctl00_mainContent_btn_FindFlights")).click();
//Handling Java Alerts using Selenium webdriver
driver.switchTo().alert().accept(); Vimp
System.out.println(driver.switchTo().alert().getText()); ok
alerts(accept)
driver.switchTo().alert().dismiss(); ok and cancel alerts(dismiss
and accept)
//How to format and align the code ctrl +shift + f
//Camel case
//debug?? ==>step into, step over, resume ???
// Refer Later
Under LEC: 70
package basics;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.os.WindowsUtils;
import org.apache.commons.io.FileUtils;
public class Miscelleanous {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C://work//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
WindowsUtils.killByName("excel.exe");
// driver.manage().deleteCookieNamed("sessionKey");
//click on any link
//login page- verify login url
/* driver.get("http://google.com");
File src=
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src,new File("C:\\Users\\rahul\\screenshot.png"));*/
//Deep dive into functional testing: Ecommerce App Testing
//Adding items to cart ECOMMERCE App
#finding the elements using text() method is not suggested since of dynamic
elements as the texts gets changes
Other Ways of Writing: Under XPATH
//div[@class='product-action'] //button[text()='ADD TO CART'] parent-
child
//div[@class='product-action']/button[text()='ADD TO CART'] parent-
child
//div //button[text()='ADD TO CART']
//div/button[text()='ADD TO CART']
//Synchronizations in Selenium:
Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it
throws a “No Such Element Exception”. ==> doesn't exist
Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions (Expected
Conditions) or maximum time exceeded before throwing “ElementNotVisibleException” exists,
but it is hidden so the webDriver cannot find and interact with it. exception. It is an intelligent
kind of wait, but it can be applied only for specified elements.
Implicit wait: wait time globally, applicable to all the scenarios
Hey wait for n(max wait) no of seconds before you throw exception. i.e. if n=5 sec and page loads
in 2 sec, it will not wait for other 3 seconds,<=DISADV.- Also Readable code-ADV, But 5 sec
applied globally-,Therefore bad performance
Explicit wait: applicable to specific(element) locator only, ADV—only where we require/targeted
elements, good performance, DISADV-more code, TYPES: 1. WebDriverWait(UNDER WAIT
INTERFACE), 2. FluentWait (UNDER WAIT INTERFACE)
//explicit wait
WebDriverWait exwait = new WebDriverWait(d, Duration.ofSeconds(5));
exwait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSele
ctor("span.promoInfo")));
Thread.Sleep: If results laoded in 3 seconds and thread.sleep(5000)…it will wait for 5 sec instead
og 3 sec…Therefore Implicit and explicit should be used….
Fluent wait: It will finds the web element reputedly at regular intervals of time until the timeout
or till the Object gets found, DISAV Code is Diff
Fluent wait is a class and an implementation of Wait interface and also parent class of
WebDriverWait.
Example:
WebDriverWait= 10 sec, continuously
FluentWait = 10 sec, polling 2 sec
Card is accepted(3rd sec)Your order is processed(7th sec) Confirmation
Example:
Select flight and enter
Search
Load 3 seconds till entire page is loaded
First flight result
Writing Other CSS and XPATH Examples: VIMP
<div id="start" xpath="1">
<button>Start</button> This Start button has to be clicked
</div>
div[id='start'] button Under CSS [Parent Child Reln]
//div[@id='start'] //button Under Xpath
//div[@id='start']/button Under Xpath
//div //button[text()='Start'] Under Xpath
To be practiced : Element_To_Be_Clickable under Waits
BELOW: Practical eg on explicit wait lec 81
package Tests;
import java.util.concurrent.TimeUnit;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class synchroniz {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","C:\\work\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://alaskatrips.poweredbygps.com/g/pt/hotels?MDPCID=ALASKA-
US.TPS.BRAND.hotels.HOTEL");
driver.findElement(By.id("H-destination")).sendKeys("nyc");
driver.findElement(By.id("H-destination")).sendKeys(Keys.TAB);
driver.findElement(By.id("H-fromDate")).sendKeys(Keys.ENTER);
WebDriverWait d=new WebDriverWait(driver,20);
d.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='resultsContainer']/
section/article[1]")));
//Thread.sleep(5000L);
driver.findElement(By.xpath("//div[@id='resultsContainer']/section/
article[1]")).click();
}
DOUBT: FluentWaitTest: Scripting difference ???
keys.tab vs click() method in selenium
??AJAX/Mouse Interactions:
Moving mouse on specific menu item and window is displayed
Actions a = new Actions(d);
a.moveToElement(d.findElement(By.xpath("//a[@id='nav-link-
accountList']"))).build().perform(); //after moving to element ==>
perform and build
Mouse Actions in Selenium:
1. doubleClick(): Performs double click on the element
2. clickAndHold(): Performs long click on the mouse without releasing it
3. dragAndDrop(): Drags the element from one point and drops to another
4. moveToElement(): Shifts the mouse pointer to the center of the element
5. contextClick(): Performs right-click on the mouse
Keyboard Actions in Selenium:
1. sendKeys(): Sends a series of keys to the element
2. keyUp(): Performs key release
3. keyDown(): Performs keypress without release .keyDown(Keys.SHIFT)
Actions: It’s a Class Refer Actions Demo src code
How to mouse over on object with selenium?
Performing mouse and keyboard interactions with selenium
Context click on element(Right Click with Selenium)
Double click on element
Drag and dropping the element
//JAVA ITERRATOR CONCEPTS: IMPPP
Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because
"iterating" is the technical term for looping. The iterator() method can be used to get an Iterator for
any collection:
// Import the ArrayList class and the Iterator class
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
// Get the iterator
Iterator<String> it = cars.iterator();
// Print the first item
System.out.println(it.next());
//Window handle concepts:
//VIPM Whn u see spaces in html for a class:
<p class="im-para red" css="1">Please email us at <strong><a
href="mailto:
[email protected]">
[email protected]</a></strong> with below template to receive
response </p>
Therefore its CSS .im-para.red or p.im-para.red and not like this p.im-para red [Tagname.class]/[.class]Under CSS
Parent and child windowWINDOW Handling
Set<String> windows = d.getWindowHandles(); //parent and
child IDs. d.getWindowHandles(): store multiple child windows in Selenium
Iterator<String> it = windows.iterator();
String parentId = it.next();
String childId = it.next();
d.switchTo().window(childId);
//VIMP when you String split, string array:
//String string = d.findElement(By.cssSelector("p.im-para.red")).getText();
//String[] email = string.split("at")[1].trim().split(" ");
//System.out.println(email[0]);
OR
String emailId =
d.findElement(By.cssSelector("p.impara.red")).getText().split("at")
[1].trim().split(" ")[0];
System.out.println(emailId);
Frames:
// Frames & DragAnd Drop
d.switchTo().frame(d.findElement(By.cssSelector("iframe.demo-frame"))); //control comes
inside the frame
Actions a = new Actions(d);
WebElement source = d.findElement(By.id("draggable")); //will click on particular element
inside the frame.
WebElement target = d.findElement(By.id("droppable"));
a.dragAndDrop(source, target).build().perform();
to know how much frames are there !...
System.out.println(d.findElements(By.tagName("iframe")).size());
// d.switchTo().frame(0); //not suggested since if developer adds another frame
in between !!!
d.switchTo().frame(d.findElement(By.cssSelector("iframe.demo-frame"))); //control comes
inside the frame
// Another method to switch to frame
// d.switchTo().frame(0);
WebElement source = d.findElement(By.id("draggable")); //will click on particular element
inside the frame.
WebElement target = d.findElement(By.id("droppable"));
a.dragAndDrop(source, target).build().perform();
What are Frames: its independent(has its own html) of html code, separate-container hosted on webpage, Selenium cant identify since
it’s a frame…
How to identify frames in application?
How to handle frames?
Best practice when working with Frames application
The Selenium WebDriver's Advanced User Interactions API allows us to perform operations from keyboard events and simple mouse events
to complex events such as dragging-and-dropping, holding a key and then performing mouse operations by using the Actions class, and
building a complex chain of events exactly like a user doing these manually. The Actions class implements the builder pattern to create a
composite action containing a group of other actions
We need to create an instance of the Actions class by passing the instance of driver class to the constructor in the following way:
Actions builder = new Actions(driver);
You can find more examples from below link: LEC 87- Action class
https://techblog.polteq.com/en/perform-a-sequence-of-actions-with-selenium-webdriver/
HTML frames allow developers to present documents in multiple views, which may be independent
windows or subwindows. Multiple views offer developers a way to keep certain information visible,
while other views are scrolled or replaced. For example, within the same window, one frame might
display a static banner, the second a navigation menu, and the third the main document that can be
scrolled through or replaced by navigating in the second frame.4
//LIMITING WEBDRIVER SCOPES
//Another Xpath Locators Examples: footer elements Under Limiting WebDriver Scope
3. COunt links of first Column
WebElement firstcol =
footerdriver.findElement(By.xpath("//table/tbody/tr/td[1]/ul"));
System.out.println(firstcol.findElements(By.tagName("a")).size());
//parentTagname/childTagname writing xpaths w/o attributes using tagnames
//OPEN LINKS IN SEPARATE TABS- :
IMP ERROR that can come: stale element reference: stale element not found
4.Click on each link in the col and check if the pages are opening
for(int i = 1 ; i < coldriver.findElements(By.tagName("a")).size() ; i++) {
String clickonlink = Keys.chord(Keys.CONTROL , Keys.ENTER); //VIMP
coldriver.findElements(By.tagName("a")).get(i).sendKeys(clickonlink); //VIMP
}
//Getting the Titles of Child tabs with optimised While loop
Set<String> windows = d.getWindowHandles();
Iterator<String> it = windows.iterator();
while (it.hasNext()) { // whether the next window is present or not
d.switchTo().window(it.next()); // driver will switch to that specific window page
System.out.println(d.getTitle());
}
//handling Calendar