selenium testing
selenium testing
Automation:
applications.
Advantages of selenium:
It is freely available automation tool. To make use of selenium for commercial purpose we
https://www.seleniumhq.org/download/
Anyone can view source code of selenium which is available in below website.
https://github.com/SeleniumHQ/selenium
Using selenium we can automate any web based applications such as gmail, facebook,
flipkart etc
It supports for 14 programming languages.
It supports for multiple platforms such as Windows, Mac, Linux.
It supports all most all the browsers such as chrome, firefox, ie, safari, opera.
Note:
1. To perform action on chrome browser, webdriver will communicate with
chromedriver.exe
2. To perform action on firefox browser, webdriver will communicate with
geckodriver.exe
3. To perform action on ie browser, webdriver will communicate with
IEDriverServer.exe
Interface:
1. SearchContext
2. JavaScriptExecutor
3. WebDriver
Classes:
1. RemoteWebDriver
2. ChromeDriver
3. InternetExplorerDriver
WebDriver methods:
1 get()
2 getTitle()
3 getCurrentUrl()
4 getPageSource()
5 findElement()
6 findElements()
7 getWindowHandle()
8 getWindowHandles()
9 switchTo()
10 manage()
11 navigate()
12 close()
13 quit()
JavascriptExecutor methods:
1 executeScript()
2 executeAsyncScript()
TakesscreenShot methods:
1. getScreenShotAs()
Note:
1. ChromeDriver class is used to work with chrome browser.
2. FirefoxDriver class is used to work with firefox browser.
3. InternetExplorerDriver class is used to work with ie browser.
Tools Required:
Download selenium jar file and driver exe files from following website.
URL http://www.seleniumhq.org/download
Extract all the driver exe files
In eclipse, create a java project with the name Automation.
Under the Java project create 2 folders with the name drivers and jars
To create folder, Right click on project new create folder
Store all extracted driver exe files under drivers folder
Store selenium jar file under jars folder
Associate selenium jar file with java project
To associate the jar file, right click on jar file Build path Add to build path
Note:
Before launching the browser we have to set path of the driver exe file.
We can set path of the driver exe file by using setProperty() of System class.
setProperty() is a static method which takes 2 args of type String. They are,
key
value
key for geckcodriver is, webdriver.gecko.driver
value is the path of the driver exe file. We can specify the value in any of the following
ways,
C:\\Users\\Venkat\\Desktop\\capgemini\\Automation\\drivers\\geckodriver.exe
C:/Users/Venkat/Desktop/capgeminis/Automation/drivers/geckodriver.exe
./drivers/geckodriver.exe(.---> path of the current java project)
If we do not set path of the driver exe file, then it will throw IllegalStateException.
BROWSER LAUNCHING
// to configure driver
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
// create the firefox driver
Quit():
Destroy the object.
It will close all browser windows opened by selenium webdriver
Chrome Launching:
chrome driver-v60=chrome driver-v2.30
}}
IE Launching:
Opera Launching:
Opera-v46=opera driver-v2.27
Output:
Write a Script to open and close the browser based on user input
public class Demo
{
public static void main(String[] args) throws InterruptedException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter brower Name:");
String browser = sc.nextLine();
if(browser.equals("Firefox"))
{
System.setProperty("webdriver.gecko.driver",
"./drivers/geckodriver.exe");
driver = new FirefoxDriver();
}
else
if(browser.equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver",
"./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
else
{
System.out.println("Invalid browser");
}
Thread.sleep(2000);
driver.close();
}
}
Note: The above script is an example for Run Time Ploymorphism.
To run same script on multiple browsers, we are converting sub class object into interface
type(upcasting).
WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver();
WEB DRIVER METHODS:
NAVIGATION COMMANDS
1. Navigate().to()
2. Refresh()
3. Back()
4. Forword()
driver.get("https://www.google.com/");
Thread.sleep(2000);
get navigate
It will just enter the URL 1. It will enter the URL
2. It will navigate to previous page
3. It will navigate to next page
4. It will refresh the current web page
After entering the URL it will
not allow any statements to
execute untill the page loads After entering the URL it will not wait
completely untill the page loads completely
WEBELEMENTS METHODS:
WebElement:
Ex:
<html>
<head>
<title>WelCome</title>
</head>
<body>
username:<input type="text">
Password:<input type="password">
<input type="button" value="Login">
<a href="http://www.gmail.com">Inbox(10)</a>
<a href="http://www.google.com" id="fp" name="forgot" class="pass">Forgot
Password???</a>
</body>
</html>
Before performing action on any elements, we have to perform following steps.
1. Inspect the element
2. Identify/locate the element
3. Find the element
4. Perform the action
LOCATORS:
Static methods which are used to identify the elements which are present the webpage.
All these locators are present in a class called By which is an Abstract class.
There are 8 types of locators and all the locators takes argument of type string. They are,
1. Id(String)
2. name(String)
3. className(String)
4. tagName(String)
5. linkText(String)
6. partialLinkText(String)
7. cssSelector(String)
8. xpath(String)
Note:
cssSelector
If we can not identify the elements by using any of the above locators, then we can identify
that element by using cssSelector.
Syntax:
ex: input[type='password']
Note:
In cssSelector,
Id can be represented by using #,
Ex:- input#email
Class can be represented by using .
Ex:- tagName.classValue
Ex,
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://adactin.com/HotelApp/index.php");
driver.manage().window().maximize();
WebElement x = driver.findElement(By.id("username"));
x.sendKeys("vengatram");
WebElement x1 = driver.findElement(By.name("password"));
x1.sendKeys("vengat@123445");
WebElement x2 = driver.findElement(By.id("login"));
x2.click();
}
}
LinkText:
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://adactin.com/HotelApp/index.php");
driver.manage().window().maximize();
WebElement x2 = driver.findElement(By.linkText("Forgot Password?"));
x2.click();
}
}
PartialLinkText:
package com.lnt.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://adactin.com/HotelApp/index.php");
driver.manage().window().maximize();
WebElement x2 = driver.findElement(By.partialLinkText("Forgot"));
x2.click();
}
}
Xpath:
Sample webpage:
<div>
A:<input type="text" value="A">
B:<input type="text" value="B">
</div><br/>
<div>
C:<input type="text" value="C">
D:<input type="text" value="D">
</div>
Absolute:
Ex:
/html/body/div[1]/input[2]
Relative xpath:
Ex:
//div[1]/input[2]
//div[1]/input
//div[2]/input
//input[1]
//div[1]/input[2]| //div[2]/input
//input
Xpath by attribute:
To identify the specified elements, if we use index it may not work properly when we use
the index values because whenever the position of an element changes its index value will
also changes.
To overcome the above problem in place of index we can include attributes which is called
as xpath by attributes.
It is applicable for both Absolute and Relative xpath.
Syntax:
Example:
Absolute /html/body/div/input[@value='B']
Relative //input[@value='B']
In an xpath we can pass multiple attributes by using or operator.
Example:
//input[@value='B' or @value='C']
Assignment:
Derive the xpath expression for the elements which are present in FaceBook login or
sign up page.
Email or Phone: //input[@type='email']
Day list box: //select[@aria-label='Day']
Male: //input[@value='2']
It is a method, used to print the value whatever you gave in the text box
Example program:
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://www.adactin.com/HotelApp/index.php");
driver.findElement(By.id("username")).sendKeys("vengat16");
driver.findElement(By.id("password")).sendKeys("Karthick");
String s = driver.findElement(By.id("username")).getAttribute("value");
String s1 = driver.findElement(By.id("password")).getAttribute("value");
System.out.println(s);
System.out.println(s1);
}
}
Output:
NoSuchElementException:
isDisplayed():
Example program:
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.facebook.com/");
boolean
logo=driver.findElement(By.xpath("//*[@id='blueBarDOMInspector']/div/div/div/div[1]/h
1/a/i")).isDisplayed();
if(logo==true)
{
System.out.println("logo is available");
}
else{
System.out.println("logo is not available");
}
}}
Output:
isEnabled:
Example program:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
boolean logo = driver.findElement(By.xpath("//*[@id='email']"))
.isEnabled();
if (logo == true) {
System.out.println("Text box is enable to print");
} else {
System.out.println("not enable");
}
Output:
isSelected:
Example program:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.xpath("//*[@id='u_0_g']"))
.click();
boolean logo = driver.findElement(By.xpath("//*[@id='u_0_g']"))
.isSelected();
if (logo == true) {
System.out.println("button is selected");
} else {
System.out.println("not selected");
}
}}
Xpath by text():
If the specified element does not contain any attributes and if it contains text then we can
identify that element by using xpath by text()
It is applicable for both absolute and relative xpath
Syntax:
Example:
//td[text()='Java']
text() can be represented by using dot(.)
Example:
//td[.='Java']
Attribute values and the text values are case and space sensitive.
Example:
//div[text()='Login ']
Xpath by contains():
While developing the application developers will be using some special characters like
&,   etc.
If the element contains any special characters then we can identify that element by using
xpath by contains().
If any value contains & symbol then it is the special character.
Example: Derive the xpath to identify Forgotten Password? Link present on facebook
login or sign up page.
//a[contains(@href,'https://www.facebook.com/recover/initiate?lwv')]
Traversing:
Navigating from one element to another element using xpath is called traversing.
To navigate from one element to another element xpath uses axis.
The different types of axis are,
1. child
2. parent
3. descendant
4. ancestor
5. following-sibling
6. preceding-sibling
Syntax:
/axis::tagName
Sample web page:
<select>
<option value="j">Jan</option>
<option value="f">Feb</option>
<option value="m">Mar</option>
<option value="a">Apr</option>
<option value="m">May</option>
</select>
Child:
Navigate from
Ex: //select//child::option[1]
Parent:
Descendant:
Ex: /html/descendant::option[1]
Ancestor:
Following-sibilng:
The elements which are present below the specified element, under same parent
are called as following-sibling.
Ex:
-sibling::option A,M
-sibling::option[1] A
-sibling::option[2] M
Preceding-sibling:
The elements which are present above the specified element, under same parent
are called as following-sibling.
Ex:
-sibling::option J,F
-sibling::option[1] F
-sibling::option[2] J
Radio button:
Example program:
Xpath:
Example program:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
for (int i = 1; i <= 2; i++) {
Thread.sleep(3000);
String s = driver.findElement(
By.xpath("//*[@id='u_0_k']/span[" + i + "]/label"))
.getText();
System.out.println(s);
}
}}
Output:
EXERCISE 1:
Program:
public class Ex3 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.adactin.com/HotelApp/index.php");
driver.findElement(By.id("username")).sendKeys("vengat16");
driver.findElement(By.id("password")).sendKeys("Karthick");
driver.findElement(By.id("login")).click();
}
Output
Program:
public class Ex4 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.adactin.com/HotelApp/index.php");
driver.findElement(By.id("username")).sendKeys("vengat16");
driver.findElement(By.id("password")).sendKeys("Karthick");
String s = driver.getCurrentUrl();
if (s.equals("http://www.adactin.com/HotelApp/index.php")) {
System.out.println("u r in adactin website");
} else {
System.out.println("u r not in adactin website");
}}}
Output
Program 3: Go to adactin.com website, give user name & password and print that user
name and password
Program:
public class Ex5 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.adactin.com/HotelApp/index.php");
driver.findElement(By.id("username")).sendKeys("vengat16");
driver.findElement(By.id("password")).sendKeys("Karthick");
String s = driver.findElement(By.id("username")).getAttribute("value");
String s1 = driver.findElement(By.id("password")).getAttribute("value");
System.out.println(s);
System.out.println(s1);
}}
Output
Program:
public class Ex10 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.xpath("//input[@name='firstname']")).sendKeys("Vengat");
driver.findElement(By.xpath("//input[@name='lastname']")).sendKeys("Ram");
driver.findElement(By.xpath("//input[@name='reg_email__']")).sendKeys("98765
43210");
driver.findElement(By.xpath("//input[@name='reg_passwd__']")).sendKeys("1234
56");
driver.findElement(By.xpath("//label[contains(text(),'Male')]")).click();
driver.findElement(By.xpath("//button[@type='submit']")).click();
}
}
Output
Program:
ublic class Ex6 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
boolean logo = driver
.findElement(
By.xpath("//*[@id='blueBarDOMInspector']/div/div/div/div[1]/h1/a/i"))
.isDisplayed();
if (logo == true) {
System.out.println("logo is available");
} else {
System.out.println("logo is not available");
}
}
}
Output
Program 6: Go to adactin.com website, give wrong user name & password and click
login. Check the error msg(invalid login details) shown or not)
Program:
public class Ex9 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.adactin.com/HotelApp/");
driver.findElement(By.id("username")).sendKeys("test");
driver.findElement(By.id("password")).sendKeys("123456");
driver.findElement(By.id("login")).click();
boolean b = driver
.findElement(
By.xpath("//*[@id='login_form']/table/tbody/tr[5]/td[2]/div/b"))
.isDisplayed();
if (b = true) {
System.out.println("invalid msg shown");
} else {
System.out.println("not");
}
}}
Output
Program 7: Go to google.com, check the google logo is available or not
Program:
public class Ex7 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
boolean logo = driver.findElement(By.xpath("//*[@id='hplogo']"))
.isDisplayed();
if (logo == true) {
System.out.println("logo is available");
} else {
System.out.println("logo is not available");
}
}
Output
Program 8: Go to google.com, click gmail and check the title is Gmail or not
Program:
public class Ex8 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a"))
.click();
String s = driver.getTitle();
if (s.equals("Gmail")) {
System.out.println("Gmail ACC");
} else {
System.out.println("Invalid");
}
}}
Output
Program 9: Gmail Account Login
Program:
public class Ex2 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&pas
sive=true&rm=false&continue=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fmail.google.com%2Fmail%2F&ss=1&
scc=1<mpl=default<mplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flow
Entry=ServiceLogin");
driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys(
"vengat161193");
driver.findElement(By.xpath("//*[@id='identifierNext']/content/span"))
.click();
Thread.sleep(3000);
driver.findElement(
By.xpath("//*[@id='password']/div[1]/div/div[1]/input"))
.sendKeys("123456");
driver.findElement(By.xpath("//*[@id='passwordNext']/content")).click();
}}
Output
Program 10: Go to facebook.com, click forgot password and give email
Program:
public class Ex1 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
driver.findElement(By.xpath("//*[@id='identify_email']")).sendKeys("vengat16");
driver.findElement(By.xpath("//*[@id='u_0_3']")).click();
}
}
Output
KeyBoard Actions using Sendkeys:
public class sampl {
public static void main(String[] args) throws InterruptedException
{
//open the browser
System.setProperty("webdriver.chrome.driver", "C:\\\\Users\\\\10655967\\\\eclipse-
workspace\\\\demo\\\\driver\\\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://adactin.com/HotelApp/index.php");
driver.manage().window().maximize();
WebElement x = driver.findElement(By.id("username"));
x.sendKeys("vengatram");
WebElement x1 = driver.findElement(By.name("password"));
x.sendKeys(Keys.CONTROL,"ac");
x1.sendKeys(Keys.CONTROL,"v");
}}
getLocation() and getSize():
Example:
public class Demo
{
WebElement un = driver.findElement(By.id("username"));
System.out.println("Height: "+h);
System.out.println("Width: "+w);
System.out.println("x-axis: "+x);
System.out.println("y-axis: "+y);
Thread.sleep(1000);
driver.close();
}
}
getCssValue():
It is used to get the css property (font, color, size) of a web element.
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://adactin.com/HotelApp/index.php");
driver.manage().window().maximize();
WebElement x =
driver.findElement(By.xpath("//td[@class='build_title']"));
String x1 = x.getCssValue("font-size");
System.out.println(x1);
String x2 = x.getCssValue("color");
System.out.println(x2);
String x3 = x.getCssValue("font-weight");
System.out.println(x3);
String x4 = x.getCssValue("font-family");
System.out.println(x4);
String x5 = x.getCssValue("background");
System.out.println(x5);
}
}
Handling multiple elements:
In order to handle multiple elements we use findElements()
Return type of findElements() is List<WebElement>
In findElements(),
If the specified locator is matching with multiple elements then it returns address
of all the matching elements
If the specified locator is not matching with any elements then it returns empty
list(0).
Note:
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();
List<WebElement> x = driver.findElements(By.tagName("a"));
System.out.println(x1.getAttribute("href"));
}
}
CHECK BOX:
In check box, we can able to select more than one value at a time.
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
driver.findElement(By.xpath(".//input[@value='dance']")).click();
}
}
output:
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
List<WebElement> w =
driver.findElements(By.xpath("//input[@type='checkbox']"));
for(WebElement x:w){
x.click();
}
}
}
Here,
//input[@type='checkbox'] if xpath we give like, we get 3 matching nodes, so
using for loop we can able to select 3 checkbox at a time
findElements is a method, used to select more than one value
WebElement is a interface
By is a class name
Output:
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
List<WebElement> w =
driver.findElements(By.xpath("//input[@type='checkbox']"));
for(WebElement x:w){
if(x.getAttribute("value").equals("dance")||x.getAttribute("value").equals("cricket
")){
x.click();
}}
}
}
Output:
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
List<WebElement> w =
driver.findElements(By.xpath("//input[@type='checkbox']"));
for(int i=0;i<w.size();i++){
w.get(i).click();
}}
}
Using normal for loop to select two checkbox:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
List<WebElement> w =
driver.findElements(By.xpath("//input[@type='checkbox']"));
for(int i=0;i<w.size();i++){
if(w.get(i).getAttribute("value").equals("dance")||w.get(i).getAttribute("value").equ
als("cricket ")){
w.get(i).click();
}}
}
}
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
List<WebElement> w = driver.findElements(By
.xpath("//input[@type='checkbox']"));
for (int i = 0; i < w.size(); i++) {
if (w.get(i).getAttribute("value").equals("dance")
|| w.get(i).getAttribute("value").equals("cricket")) {
w.get(i).click();
}
if (w.get(i).isSelected()) {
System.out.println(w.get(i).getAttribute("value"));
}
}
}
}
Output:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demoqa.com/registration/");
List<WebElement> w = driver.findElements(By
.xpath("//input[@type='checkbox']"));
for (int i = 0; i < w.size(); i++) {
if (w.get(i).getAttribute("value").equals("dance")
|| w.get(i).getAttribute("value").equals("cricket")) {
w.get(i).click();
}
if (!w.get(i).isSelected()) {
w.get(i).click();
}
}
}
}
Output:
Handling auto-suggestions
We can handle auto suggestions by using findElements().
Example:WAS for the following scenario.
Navigate to google
Search for qspiders
Count and print all the auto-suggestions
Click on last suggestion
public class Login {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
}
Difference between findElement() & findElements():
findElement() findElements()
To handle single element To handle multiple elements
Return type is WebElement Return type is List<WebElement>
if the specified locator is
if the specified locator is matching
matching multiple elements then it returns
multiple elements then it returns address of all the matching
address of 1st matching element element
if the specified locator is not if the specified locator is not
matching then it returns matching then it returns empty
NoSuchElementException list(0)
DROP DOWN:
1.Single value
2.Multiple value
If the list box is developed by using select tag then we can handle it by using Select class.
Select class should be imported from the package org.openqa.selenium.support.ui
Select class contains one constructor which takes an argument of type WebElement where
in we have to pass address of the list box.
Select class contains some methods. They are,
1 selectByIndex(int)
2 selectByValue(String) Select the options
3 selectByVisibleText(String)
4 deselectByIndex(int)
5 deselectByValue(String)
Deselect the options
6 deselectByVisibleText(String)
7 deselectAll()
8 getAllSelectedOptions() To get all the selected options
9 getFirstSelectedOption() To get first selected options
10 getOptions() To get all the options
11 isMultiple() To check whether list box is single or multi select
1.SINGLE VALUE
To print all the options:
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
List<WebElement> o = s.getOptions();
for (WebElement x:o) {
System.out.println(x.getAttribute("value"));
}
}
}
Output:
To print all text
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
List<WebElement> o = s.getOptions();
for (WebElement x:o) {
System.out.println(x.getText());
}
}
}
Output :
Using normal for loop:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
List<WebElement> o = s.getOptions();
for (int i=0;i<=o.size();i++) {
System.out.println(o.get(i).getAttribute("value"));
}
}
}
Here,
getAttribute() to print particular tag(value) value
getText() to print all text
SELECT:
We can perform select by 3 ways
1. SelectByIndex
2. SelectByValue
3. SelectByVisibletext
1.selectByIndex:
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
s.selectByIndex(3);
}
}
Output:
2.selectByValue:
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
s.selectByValue("regular");
}
}
3.selectByVisibletext:
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
s.selectByVisibleText("With cream & sugar");
}
}
getAllSelectedOptions()
It is a method, used to print all selected options
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee"));
Select s=new Select(w);
List<WebElement> web = s.getAllSelectedOptions();
for(WebElement x:web){
System.out.println(x.getText());
} }}
Output:
Note:
2.MULTIPLE VALUE
isMultiple():
It is a method, used to check we can able to select multiple values or not
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee2"));
Select s=new Select(w);
boolean b = s.isMultiple();
System.out.println(b);
}
}
Output:
SelectByIndex:
Eample program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee2"));
Select s=new Select(w);
List<WebElement> web = s.getOptions();
for(int i=0;i<web.size();i++){
s.selectByIndex(i);
}
}
}
Output:
2.selectByValue
Example Program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee2"));
Select s=new Select(w);
List<WebElement> web = s.getOptions();
s.selectByValue("skim");
s.selectByValue("whipped");
}
}
Output:
Note:
In multi-select list box, if the specified option is duplicate then it will select all the
matching options.
We can handle duplicates by using index.
EXERCISE 2:
Program 1: Gmail registration
Program:
public class Ex2 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3
A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
driver.findElement(By.xpath("//input[@id='FirstName']")).sendKeys(
"Vengat");
driver.findElement(By.xpath("//input[@id='LastName']")).sendKeys("Ram");
driver.findElement(By.xpath("//input[@id='GmailAddress']")).sendKeys(
"Vengat161193");
driver.findElement(By.xpath("//input[@id='Passwd']"))
.sendKeys("123456");
driver.findElement(By.xpath("//input[@id='PasswdAgain']")).sendKeys(
"123456");
driver.findElement(By.xpath(".//*[@id='BirthMonth']/div[1]")).click();
driver.findElement(By.xpath("//div[contains(text(),'November')]"))
.click();
driver.findElement(By.xpath(".//input[@id='BirthDay']")).sendKeys("16");
driver.findElement(By.xpath(".//input[@id='BirthYear']")).sendKeys(
"1993");
driver.findElement(By.xpath(".//*[@id='Gender']/div[1]")).sendKeys(
"Male");
driver.findElement(By.xpath("//input[@id='RecoveryPhoneNumber']"))
.sendKeys("9876543210");
driver.findElement(By.xpath("//input[@id='RecoveryEmailAddress']"))
.sendKeys("venkat12345@gmail.com");
driver.findElement(By.xpath("//*[@id=':i']")).click();
driver.findElement(By.xpath("//div[contains(text(),'India')]")).click();
driver.findElement(By.xpath(".//*[@id='submitbutton']")).click();
}
}
Output:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.xpath("//input[@name='firstname']")).sendKeys(
"Vengat");
driver.findElement(By.xpath("//input[@name='lastname']")).sendKeys(
"Ram");
driver.findElement(By.xpath("//input[@name='reg_email__']")).sendKeys(
"9876543210");
driver.findElement(By.xpath("//input[@name='reg_passwd__']")).sendKeys(
"123456");
WebElement w1 = driver.findElement(By.xpath("//*[@id='day']"));
Select s1 = new Select(w1);
s1.selectByValue("16");
WebElement w2 = driver.findElement(By.xpath("//*[@id='month']"));
Select s2 = new Select(w2);
s2.selectByValue("11");
WebElement w3 = driver.findElement(By.xpath("//*[@id='year']"));
Select s3 = new Select(w3);
s3.selectByValue("1993");
driver.findElement(By.xpath("//label[contains(text(),'Male')]"))
.click();
driver.findElement(By.xpath("//button[@type='submit']")).click();
}
}
Output:
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://login.yahoo.com/account/create?specId=yidReg&altreg=0&intl
=in&.done=http://in.mail.yahoo.com");
driver.findElement(By.xpath("//input[@id='usernamereg-
firstName']")).sendKeys("Vengat");
driver.findElement(By.xpath("//input[@id='usernamereg-
lastName']")).sendKeys("Ram");
driver.findElement(By.xpath("//input[@id='usernamereg-
yid']")).sendKeys("vengat12344444");
driver.findElement(By.xpath("//input[@id='usernamereg-
password']")).sendKeys("venkat12345");
driver.findElement(By.xpath("//input[@id='usernamereg-
phone']")).sendKeys("98765430001");
WebElement w =
driver.findElement(By.xpath("//select[@id='usernamereg-month']"));
Select s=new Select(w);
s.selectByValue("11");
driver.findElement(By.xpath("//input[@id='usernamereg-
day']")).sendKeys("16");
driver.findElement(By.xpath("//input[@id='usernamereg-
year']")).sendKeys("1993");
driver.findElement(By.xpath("//input[@id='usernamereg-
freeformGender']")).sendKeys("Male");
Thread.sleep(3000);
driver.findElement(By.xpath("//button[@id='reg-submit-button']")).click();
}
}
Output:
Program 4: Linkedin login
public class Ex6 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://in.linkedin.com/");
driver.findElement(By.xpath("//input[@id='reg-firstname']")).sendKeys(
"Vengat");
driver.findElement(By.xpath("//input[@id='reg-lastname']")).sendKeys(
"Ram");
driver.findElement(By.xpath("//input[@id='reg-email']")).sendKeys(
"vengat12345@gmail.com");
driver.findElement(By.xpath("//input[@id='reg-password']")).sendKeys(
"9876543210");
driver.findElement(By.xpath("//input[@id='registration-submit']")).click();
}}
Output:
Program 5: Twitter registration
public class Ex4 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:/Users/siva/workspace/Selenium/
driver/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://twitter.com/signup?lang=en");
driver.findElement(By.xpath("//*[@id='full-
name']")).sendKeys("vengat");
driver.findElement(By.xpath("//*[@id='email']")).sendKeys("venkat1234500@gm
ail.com");
Thread.sleep(3000);
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("11111111");
driver.findElement(By.xpath("//*[@id='submit_button']")).click();
}
}
Output:
Program 6: Instagram registration
public class Ex7 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.instagram.com/?hl=en");
driver.findElement(By.xpath("//input[@name='emailOrPhone']")).sendKeys(
"Vengat");
driver.findElement(By.xpath("//input[@name='fullName']")).sendKeys(
"Ram");
driver.findElement(By.xpath("//input[@name='username']")).sendKeys(
"vengat12345@gmail.com");
driver.findElement(By.xpath("//input[@name='password']")).sendKeys(
"9876543210");
driver.findElement(By.xpath("//*[@id='react-
root']/section/main/article/div[2]/div[1]/div/form/div[6]/span/button")).click();
}
}
Output:
Program 7: Skype registration
public class Ex8 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://signup.live.com/signup?lcid=1033&wa=wsignin1.0&rpsnv=13
&ct=1499100057&rver=6.7.6626.0&wp=MBI_SSL&wreply=https%3a%2f%2ffanyv88.com%3a443%2fhttps%2flw.skype.c
om%2flogin%2foauth%2fproxy%3fform%3dmicrosoft_registration%26site_name%3dlw.
skype.com%26fl%3dphone2&lc=1033&id=293290&mkt=en-
IN&uaid=41725f7d178ae3acfc20174e1190cd1b&psi=skype&lw=1&cobrandid=90010&cl
ient_flight=hsu%2cReservedFlight33%2cReservedFlight67&fl=phone2&lic=1");
driver.findElement(By.xpath("//input[@id='MemberName']")).sendKeys(
"9876543221");
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(
"Venkat122333");
driver.findElement(By.xpath("//input[@id='iSignupAction']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//input[@id='FirstName']")).sendKeys(
"Venkat");
driver.findElement(By.xpath("//input[@id='LastName']")).sendKeys(
"Ram");
driver.findElement(By.xpath("//input[@id='iSignupAction']")).click();
}}
Output:
Program 8: Make my trip registration
public class Ex9 {
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.makemytrip.com/");
driver.findElement(By.xpath("//a[@id='ch_signup_icon']")).click();
driver.findElement(By.xpath("//input[@id='ch_signup_email']")).sendKeys(
"Venkat122333@gmail.com");
driver.findElement(By.xpath("//input[@id='ch_signup_phone']")).sendKeys("9876
543221");
driver.findElement(By.xpath("//input[@id='ch_signup_password']")).sendKeys(
"Venkat123");
driver.findElement(By.xpath("//button[@id='ch_signup_btn']")).click();
//driver.findElement(By.xpath("//input[@id='iSignupAction']")).click();
}
}
Output:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.spicinemas.in/user/register");
driver.findElement(By.xpath("//input[@id='email']")).sendKeys("venkat122333@
gmail.com");
driver.findElement(By.xpath("//input[@id='password']")).sendKeys(
"Venkat54321");
driver.findElement(By.xpath("//input[@id='passwordVerify']")).sendKeys("Venka
t54321");
driver.findElement(By.xpath("//input[@id='name']")).sendKeys(
"Venkat");
driver.findElement(By.xpath("//input[@id='lastName']")).sendKeys(
"Ram");
driver.findElement(By.xpath("//input[@id='dob']")).sendKeys("16-11-
1993");
driver.findElement(By.xpath("//input[@id='genderMale']")).click();
driver.findElement(By.xpath("//input[@id='address']")).sendKeys(
"No.38, west saidapet");
driver.findElement(By.xpath("//input[@id='pincode']")).sendKeys(
"600015");
driver.findElement(By.xpath("//input[@id='city']")).sendKeys("chennai");
driver.findElement(By.xpath("//input[@id='terms-and-
condition']")).click();
driver.findElement(By.xpath("//button[@id='subscriptionStatus']")).click();
driver.findElement(By.xpath("//input[@id='register']")).click();
}
Deselect:
1. deselect by value
2. deselect by index
3. deselect by visible text
4. deselect all
1. deselect by value:
Example program:
public class Dummy {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee2"));
Select s=new Select(w);
List<WebElement> web = s.getOptions();
for(int i=0;i<web.size();i++){
s.selectByIndex(i);
Thread.sleep(3000);
s.deselectByIndex(i);
}
}
}
Output :
2. Deselect By Value :
Example Program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee2"));
Select s=new Select(w);
List<WebElement> web = s.getOptions();
s.selectByValue("skim");
s.selectByValue("whipped");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s.deselectByValue("skim");
s.deselectByValue("whipped");
}}
Output:
3. Deselect By VisibleText:
Example program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://ironspider.ca/forms/dropdowns.htm");
WebElement w = driver.findElement(By.name("coffee2"));
Select s=new Select(w);
List<WebElement> web = s.getOptions();
s.selectByVisibleText("Sugar");
s.selectByVisibleText("Honey");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s.deselectByVisibleText("Sugar");
s.deselectByVisibleText("Honey");
}
}
Output :
WEB TABLE:
tr Table row
th Table heading
td Table data
To print particular values(data) in the table:
Example program:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/automation-practice-table/");
String s =
driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[2]/td[2]")).getText();
System.out.println(s);
}}
Output:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/automation-practice-table/");
List<WebElement> tRows = driver.findElements(By.tagName("tr"));
for(WebElement rows:tRows){
List<WebElement> tData = driver.findElements(By.tagName("td"));
for(WebElement data:tData){
System.out.println(data.getText());
}
}
}
Output:
Using normal for loop:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/automation-practice-table/");
List<WebElement> tRows = driver.findElements(By.tagName("tr"));
for(int i=0;i<tRows.size();i++){
List<WebElement> tData = driver.findElements(By.tagName("td"));
for(int j=0;j<tData.size();j++){
System.out.println(tData.get(j).getText());
}
}
}
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/automation-practice-table/");
List<WebElement> tRows = driver.findElements(By.tagName("tr"));
for(int i=0;i<tRows.size();i++){
List<WebElement> tData = driver.findElements(By.tagName("td"));
for(int j=0;j<tData.size();j++){
if(tData.get(j).getText().equals("Mecca")){
System.out.println(tData.get(j).getText());
}
}}}
Output:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/automation-practice-table/");
List<WebElement> tRows = driver.findElements(By.tagName("tr"));
for(int i=0;i<tRows.size();i++){
List<WebElement> tData = driver.findElements(By.tagName("td"));
for(int j=0;j<tData.size();j++){
if(tData.get(j).getText().equals("Dubai")){
driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr["+i+"]/td[6]/a"));
System.out.println(tData.get(j).getText());
}
}
}
}
JavascriptExecutor:
Example:
Write a Script to scroll down and scroll up the window using pixel
public class Login {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10655967\\eclipse-
workspace\\demo\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.seleniumhq.org/download/");
Thread.sleep(3000);
//To scroll up
j.executeScript("window.scrollBy(0,-500)");
Note:
Here widow represents current window and scrollBy is a method to scroll the window
Example2 :
Write a Script to scroll down and scroll up the window upto 50px for 10 times
public class Login {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10655967\\eclipse-
workspace\\demo\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.seleniumhq.org/download/");
Thread.sleep(3000);
//To scroll up
for (int i = 0; i < 10; i++) {
j.executeScript("window.scrollBy(0,-50)");
Thread.sleep(500);
}
Example3 :
Write a Script to scroll web page upto specified element
Example Program:
Example4 :
Write a Script to enter textbox value and click using javascript
Syntax:
JavascriptExecutor js=(JavascriptExecutor) driver;
js.executeScript("document.getElementById('email').setAttribute('value','Hello')");
Another method
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
//java script declaration
JavascriptExecutor js=(JavascriptExecutor) driver;
js.executeScript("document.getElementById('email').setAttribute('value','Hello')");
// to print the value
Object s = js.executeScript("return document.getElementById('email').
getAttribute('value')");
System.out.println(s);
// to click login
js.executeScript("return document.getElementById('u_0_r').click()");
}}
Another method:
public class Dummy {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
//java script declaration
JavascriptExecutor js=(JavascriptExecutor) driver;
email
js.executeScript("arguments[0].setAttribute('value','Hello')",w);
WebElement w1=driver.findelement(By.Id('u_0_r');
js.executeScript("arguments[0].click()",w1);
}}
In this method, we can scroll down one single page from the first page
public class dummy1 {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://adactin.com/HotelApp/index.php");
j.executeScript("arguments[0].setAttribute('style','background: green;
border: solid 2px red');", username);
username.sendKeys("venkat");
j.executeScript("arguments[0].setAttribute('style','background: green;
border: solid 2px red');", password);
username.sendKeys("venkat@1234");
Thread.sleep(2000);
login.click();
}
SCREENSHOT:
Takescrenshot interface
Example program:
public class Dummy {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.id("email")).sendKeys("Hello");
//screenshot declaration
TakesScreenshot tk=(TakesScreenshot) driver;
File source= tk.getScreenshotAs(OutputType.FILE);
File des=new File("F:/facebook.png");
FileUtils.copyFile(source,des );
}}
Output:
MOUSE HOVER ACTION:
Actions:
Note:
When we are using any methods of Actions class, then it is mandatory to call perform()
Until unless we call perform(), Actions class will never perform the actions.
When we move the cursor on an element, a list of menus will be displayed. These type of
elements are called as Drop down menus.
We can handle this drop down menu or mouse over action using moveToElement() of
Actions class
Example:
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.greenstechnologys.com/");
a.moveToElement(courses).perform();
Thread.sleep(2000);
WebElement devOpTraining =
driver.findElement(By.xpath("//span[text()='DevOps Training']"));
a.click(devOpTraining).perform();
We can handle this drag and drop action using dragAndDrop() of Actions class.
dragAndDrop() takes 2 argument of type WebElement. They are,
source
target
Example:
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/test/drag_drop.html");
WebElement des =
driver.findElement(By.xpath("(//li[@class='placeholder'])[1]"));
Thread.sleep(2000);
a.dragAndDrop(source, des).perform();}}
How to perform drag and drop action without using dragAndDrop()?
Ans: act.clickAndHold(src).moveToElement(target).release().perform();
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/test/drag_drop.html");
WebElement des =
driver.findElement(By.xpath("(//li[@class='placeholder'])[1]"));
Thread.sleep(2000);
a.clickAndHold(source).moveToElement(des).release(des).perform();
}
RIGHT CLICK:
Handling context click action:
Example:
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
Thread.sleep(2000);
a.contextClick(gmail).perform();
// Using robot class we can open gmail in new tab
r.keyPress(KeyEvent.VK_DOWN);
r.keyRelease(KeyEvent.VK_DOWN);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
Actions Methods
Drop down menu/Mouse over moveToElement()
Drag and Drop dragAndDrop()
Double click doubleClick()
Context click(Right click) contextClick()
Composite Action build().perform()/perform()
EXERCISE:
1.Go to flipkart,com, click mobile case using mouse over action,&check the particular
title is correct and take screenshot :
public class Ex2 {
public static void main(String[] args) throws IOException, InterruptedException
{
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.flipkart.com/");
WebElement web =
driver.findElement(By.xpath(".//*[text()='Electronics']"));
Actions a=new Actions(driver);
a.moveToElement(web).perform();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[text()='Mobile Cases']")).click();
String s = driver.getCurrentUrl();
if(s.equals("https://www.flipkart.com/mobile-accessories/cases-and-
covers/pr?sid=tyy,4mr,q2u&otracker=nmenu_sub_Electronics_0_Mobile%20Cases")){
System.out.println("u r in mobile case page");
}else
{
System.out.println("u r not in mobile case");
}
Thread.sleep(3000);
TakesScreenshot tk=(TakesScreenshot) driver;
File f = tk.getScreenshotAs(OutputType.FILE);
File f1=new File("F:/flipkart mobile case.png");
FileUtils.copyFile(f,f1 );
Output:
2.Adactin.com registration:
public class Ex3 {
public static void main(String[] args) throws IOException, InterruptedException
{
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.adactin.com/HotelApp/index.php");
driver.findElement(By.id("username")).sendKeys("vengat16");
driver.findElement(By.id("password")).sendKeys("Karthick");
driver.findElement(By.id("login")).click();
driver.findElement(By.id("location")).sendKeys("London");
driver.findElement(By.id("hotels")).sendKeys("Hotel Sunshine");
driver.findElement(By.id("room_type")).sendKeys("Super Deluxe");
driver.findElement(By.id("room_nos")).sendKeys("3 - Three");
driver.findElement(By.id("datepick_in")).sendKeys("11/07/2017");
driver.findElement(By.id("datepick_out")).sendKeys("12/07/2017");
driver.findElement(By.id("adult_room")).sendKeys("2 - Two");
driver.findElement(By.id("child_room")).sendKeys("2 - Two");
driver.findElement(By.id("Submit")).click();
driver.findElement(By.id("radiobutton_0")).click();
driver.findElement(By.id("continue")).click();
driver.findElement(By.id("first_name")).sendKeys("Vengat");
driver.findElement(By.id("last_name")).sendKeys("Ram");
driver.findElement(By.id("address")).sendKeys("no.20, dubai kurukku
santhu,dubai");
driver.findElement(By.id("cc_num")).sendKeys("1234567890123456");
driver.findElement(By.id("cc_type")).sendKeys("VISA");
driver.findElement(By.id("cc_exp_month")).sendKeys("March");
driver.findElement(By.id("cc_exp_year")).sendKeys("2020");
driver.findElement(By.id("cc_cvv")).sendKeys("123");
driver.findElement(By.id("book_now")).click();
}}
Output:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/signin/v2/identifier?service=mail&passive
=true&rm=false&continue=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fmail.google.com%2Fmail%2F&ss=1&scc
=1<mpl=default<mplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEnt
ry=ServiceLogin");
Thread.sleep(5000);
WebElement w =
driver.findElement(By.xpath(".//*[@id='identifierId']"));
JavascriptExecutor js=(JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('value','venkat12345')",w);
WebElement w1 =
driver.findElement(By.xpath(".//*[text()='Next']"));
js.executeScript("arguments[0].click()",w1);
Thread.sleep(6000);
WebElement w2 =
driver.findElement(By.xpath("//*[@name='password']"));
js.executeScript("arguments[0].setAttribute('value','venkat12345')",w2);
Thread.sleep(6000);
WebElement w3 =
driver.findElement(By.xpath(".//*[@id='passwordNext']/div[2]"));
js.executeScript("arguments[0].click()",w3);
}}
ALERTS:
1. Simple:
In this method, we just click single ok button in the alert.
Example program:
public class Dummy2 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
driver.findElement(By.xpath("//input[@type='submit']")).click();
Alert a = driver.switchTo().alert();
System.out.println(a.getText());
a.accept();
driver.switchTo().defaultContent();
driver.findElement(By.id("login1")).sendKeys("venkat123");
driver.quit();
}
}
Here,
alert class
Output:
2. Confirm:
In this method, we have to click OK or Cancel, if we click OK/Cancel, then it
will confirm
Example program:
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/handling-alerts-using-selenium-webdriver/");
driver.findElement(By.xpath(".//button[text()='Confirm Pop up']")).click();
Alert a = driver.switchTo().alert();
System.out.println(a.getText());
a.dismiss();
driver.quit();}
Output:
3. Prompt:
In this method, first we have insert Yes/No and then we will click OK/Cancel
Example program:
public class Dummy4 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.com/handling-alerts-using-selenium-webdriver/");
driver.findElement(By.xpath(".//button[text()='Prompt Pop up']")).click();
Alert a = driver.switchTo().alert();
System.out.println(a.getText());
a.sendKeys("yes");
Thread.sleep(3000);
a.dismiss();
driver.quit();
}
Output:
WINDOW HANDLING:
It is used to move one window to another window
Example :
To Handle 2 windows:
public class Dummy9 {
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.hdfcbank.com/");
driver.findElement(By.xpath(".//*[@id='cee_closeBtn']/img")).click();
String parentWindowId = driver.getWindowHandle();
System.out.println("Parent Window ID:" + parentWindowId);
driver.findElement(By.id("loginsubmit")).click();
Set<String> allWindowId = driver.getWindowHandles();
for (String x : allWindowId) {
if (!parentWindowId.equals(x)) {
System.out.println("Child Window ID:" + x);
driver.switchTo().window(x);
Thread.sleep(3000);
driver.findElement(By.xpath("html/body/div[4]/div[2]/div[1]/a"))
.click();
driver.manage().window().maximize();
Thread.sleep(2000);
driver.switchTo().defaultContent();
}
}
Thread.sleep(3000);
driver.quit(); }
}
Here,
Home page(window) parent window
Next window Child window
getWindowHandle() It is a method used to get parent window id
getWindowHandles() It is a method used to get all windows id
C all windows id
We have to find B using Iterator or enhancement for
defaultContent() it is a method used to move previous window
Output:
To Handling Multiple windows:
public class Login {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\10657527\\Downloads\\chromedriver_win32
(1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.hdfcbank.com/");
driver.findElement(By.xpath(".//*[@id='cee_closeBtn']/img")).click();
String parentWindowId = driver.getWindowHandle();
System.out.println("Parent Window ID:" + parentWindowId);
driver.findElement(By.id("loginsubmit")).click();
Set<String> allWindowId = driver.getWindowHandles();
IFRAME:
IFrame is a web page which is embedded in another web page or an HTML document
embedded inside another HTML document.
iFrame is defined by an <iframe></iframe> tag in HTML. With this tag you can identify
an iFrame while inspecting the HTML tree.
Same HTML for IFrame,
<body>
<div class="box">
<iframe name="iframe1" id="IF1" height="600"
width="400"
src="http://toolsqa.wpengine.com"></iframe>
</div>
<div class="box">
<iframe name="iframe2" id="IF2" height="600" width="400"
align="left" src="http://demoqa.com"></iframe>
</div>
</body>
</html>
Identifying IFrame:
We cannot detect the frames by just seeing the page or by inspecting Firebug.
Observe the below image, Advertisement being displayed is an Iframe, we cannot locate
or recognize that by just inspecting using Firebug. So the question is how can you
identify the iframe?
Right click on the element, If you find the option like 'This Frame' then it is an
iframe.(Please refer the above diagram)
Right click on the page and click 'View Page Source' and Search with the 'iframe', if you
can find any tag name with the 'iframe' then it is meaning to say the page consisting an
iframe.
@Test
public void upload() throws InterruptedException, IOException
{ System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.wpengine.com/iframe-practice-page/");
int size =
driver.findElements(By.tagName("iframe")).size();
System.out.println(size);
driver.switchTo().frame(0);
driver.findElement(By.name("firstname")).sendKeys("vengat");
}
}
Using ID:
public class Dummy9 {
@Test
public void upload() throws InterruptedException, IOException {
System.setProperty("webdriver.gecko.driver",
driver.findElement(By.name("firstname")).sendKeys("vengat");
}
}
Using Name:
@Test
public void upload() throws InterruptedException, IOException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.wpengine.com/iframe-practice-page/");
int size = driver.findElements(By.tagName("iframe")).size();
System.out.println(size);
driver.switchTo().frame("iframe1");
driver.findElement(By.name("firstname")).sendKeys("vengat");
}
}
@Test
public void upload() throws InterruptedException, IOException {
System.setProperty("webdriver.gecko.driver",
"C:/Users/siva/workspace/Selenium/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://toolsqa.wpengine.com/iframe-practice-
page/"); int size =
driver.findElements(By.tagName("iframe")).size();
System.out.println(size);
WebElement web =
driver.findElement(By.id("IF2"));
driver.switchTo().frame(web);
driver.findElement(By.name("firstname")).sendKeys("venga
t");
}
}