Contents
1.  History of Selenium
2.  Selenium Architecture
3.  Selenium Java Architecture
4.  Locators
        4.1 X path
                   4.1.1 Handling completely dynamic elements
5. WebElement
        5.1 Font Size
        5.2 Height
        5.3 Color
        5.4 Etc.
6. Handling Dropdowns (Sorting, Duplicates)
7. TakesScreenshot
        7.1 Generic methods to capture the screenshot
8. Pop-ups (6 Pop-ups along with window popup)
9. Frames
10. JavaScriptExecuter
        10.1 Pass the data
        10.2 Clear the data
        10.3 Performs scroll action
        10.4 Scroll down to specific element
        10.5 Zoom in and zoom out the pages
11. Data Driven Testing
12. Read single data from Excel
        12.1 Write single data into Excel
        12.2 Read multiple data from Excel
        12.3 Write multiple data into Excel
        12.4 Generic read data
13. Synchronization
        13.1 Implicit Wait
        13.2 Explicit Wait
        13.3 Fluent Wait
14. TestNG
        14.1 Assertions
        14.2 Parallel Execution
        14.3 Groups
        14.4 Dependencies
        14.5 Parameters
        14.6 Listeners
15. PageObjectModel (POM)
         15.1 Integrating Generic Methods
16.   Hybrid Framework
17.   Maven Project
         17.1 Conversion of Java Project to Maven
         17.2 Adding Dependencies
         17.3 Adding Plugins
         17.4 Execution of Framework
18.   GitHub
         18.1 Push
         18.2 Pull
         18.3 Commit
         18.4 Merge
19.   Genkins
20.   Reporting Tools
         20.1 Log4J
         20.2 Extent Reports
21.   Property Files
22.   Java Database Connectivity (JDBC)
         1.History of Selenium
                 Selenium was invented by Jason Huggins in the year 2004.
                 Selenium is free and open-source web-based automation tool.
                 Free - We need not to pay to download Selenium.
                 Open Source – We can view, modify, download the source code.
                 Selenium supports 14 programming languages out of which 5 languages are primarily
                  used that is., Java, C#, Python, Ruby, JavaScript.
                 Selenium supports almost all the browsers. (6-7 Browsers)
         Flavors or Version of Selenium
                 Selenium Core – Here we cannot run multiple scrips at one shot.
                 Selenium IDE (Integrated Development Environment) – Only click action was possible
                  and mouse hovering was not entertained.
                 Selenium RC (Remote Control) – It doesn’t support secured protocols that is., HTTPS
                  was not supported.
                 Selenium WebDriver – All possible manual actions can be automated through
                  Selenium WebDriver.
         2.Selenium Architecture
Client Binding/                Selenium
Language Binding                                                    Driver                         Browser
                               Server
Java
C#                              WebDriver                      Chromedriver.ex
Python                                                                                             Chrome
                                Version                        e
Ruby                                                                                            Mozilla Firefox
Java Script                     3.141.59.jar                   Geckodriver.exe
Etc.
                                14 Programming
                                                                   Action                    JSON Wire Protocol
                                   Languages
                 Selenium is a tool which supports 14 programming languages. All these languages
                  are called as Client Binding or Language Binding.
                 These Client Binding or Language Binding will interact with the Selenium server and
                  the Selenium server will perform actions on the browser with the help of Driver files.
                 Here, Driver files are acting like a translator or intermediate between Selenium
                  server and browser.
       While Selenium server is interacting with the browser it will use a protocol called
        JSON wire protocol (JavaScript Object Notation).
       In order to specify type of browser and path of the driver file we use below
        statement. [System.setProperty(key, value)].
       We use to establish relationship between browser and Selenium
Required Software’s for Selenium Installation
       Java JDK 1.8
       Selenium Server – 3.141.59.jar
       Driver Files:
                          1. Chrome Browser – Chromedriver.exe
                          2. Mozilla Firefox – Geckodriver.exe
Write a script to launch an empty Chrome browser
package basicScripts;
import org.openqa.selenium.chrome.ChromeDriver;
public class Script1
{
public static void main(String[] args)
        {
               String key = "webdriver.chrome.driver";
               String value = "./Softwares/chromedriver.exe";
               System.setProperty(key, value);
               ChromeDriver driver=new ChromeDriver();
        }
}
Explain the below statement
ChromeDriver driver = new ChromeDriver();
       ChromeDriver -> It is a ClassType
       Driver -> It is a reference variable. It consists of the address of Browser/Application.
       ‘=’ -> It is an Assignment Operator.
       new -> It is a Keyword. It creates a Random Memory Space in the Heap Memory and
        also it help in creating the object.
       ChromeDriver() -> It is a Constructor. It will Initialize all the non-static members of
        the class and also it will launch the empty chrome browser.
Write a script to launch an empty Firefox browser
package basicScripts;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Script2
{
public static void main(String[] args)
        {
               String key ="webdriver.gecko.driver";
               String value ="./Softwares/geckodriver.exe";
               System.setProperty(key, value);
               FirefoxDriver driver= new FirefoxDriver();
        }
}
Explain Below Statement
FirefoxDriver driver = new FirefoxDriver();
       FirefoxDriver -> It is a ClassType
       Driver -> It is a reference variable. It consists of address of Browser/Application.
       ‘=’ -> It is an Assignment Operator.
       new -> It is a Keyword. It creates a Random Memory Space in the Heap Memory and
        also it help in creating the object.
       FirefoxDriver() -> It is a Constructor. It will Initialize all the non-static members of the
        class and also it will launch the empty chrome browser.
Write a script to launch empty Chrome browser and Firefox
browser
package basicScripts;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Script3
{
        public static void main(String[] args)
        {
                String key ="webdriver.gecko.driver";
                String value ="./Softwares/geckodriver.exe";
                System.setProperty(key, value);
                FirefoxDriver driver= new FirefoxDriver();
                String key1 = "webdriver.chrome.driver";
                String value1 = "./Softwares/chromedriver.exe";
                System.setProperty(key1, value1);
                ChromeDriver driver1=new ChromeDriver();
        }
}
Note: Here ‘ . ’ represents current Java project and ‘ / ’ represents to navigate from one
folder to another.
3.Selenium Java Architecture
                                          Search Context
                                                        Extends
                                            WebDriver
                                                     Implements
                                      Remote WebDriver
            Extends                                                    Extends
                                                        Extends
Chrome Driver                             Firefox Driver                         IE Driver
       Search Context is the super most Interface which has 2 Abstract Methods.
       Web Driver is an Interface that extends Search Context and it has 13 Abstract
        Methods (11 Abstract Methods + 2 Extended Abstract Methods).
       Remote WebDriver is a class that Implements WebDriver and it consists of 13
        Concrete Methods. All the properties of WebDriver are Implemented in Remote
        WebDriver, so it is called Implementation Class.
       Around 2000 class Inherit from Remote WebDriver, but only 6-7 are browser classes.
       WebDriver driver = new ChromeDriver()
       Throughout the architecture the Selenium tool takes the support of Java language
        with concepts such as Inheritance, Upcasting, Abstraction, Overriding, Operators,
        Constructor, Keywords, etc.
Write a Script to launch empty Firefox browser by
achieving RTP (Runtime Polymorphism)
Public class Script1
{
        public static void main(String[] args)
        {
        System.setProperty(key, value);
        WebDriver driver= new ChromeDriver();
       }
}
Methods of WebDriver Interface
Method                                        Return Type
    1. Close()                                void
    2. findElements()
    3. equals(Object obj): Boolean – Object
Methods of Search Context
findElements
findElements(Bya
Write a script to launch the Chrome browser and close it
{
Public static void main(String[] args)
Throws InterruptedException
{
System.setProperty(key,value);
WebDriver driver=new ChromeDriver();
Thread.sleep(2000);
driver.close(); //Closes single tab
driver.quit(); //Closes all tabs
}
Difference between close method and quit method
                      Close                                         Quit
              1. It closes single tab.                      1. It closes all the tabs.
     2. It doesn’t kill the backend process.           2. It kills the backend process.
Write a script to Maximize a browser
package basicScripts;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MaxBrowser
{
        public static void main(String[] args) throws InterruptedException
        {
        System.setProperty("webdriver.chrome.driver","./Softwares/chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        Thread.sleep(2000);
        driver.manage().window().maximize();
        }
}
Write a script to fetch the title, URL and source code of
Facebook page
package basicScripts;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetforFB
{
       public static void main(String[] args) throws InterruptedException
       {
System.setProperty("webdriver.chrome.driver","./Softwares/chromedriver.
exe");
               WebDriver driver=new ChromeDriver();
               Thread.sleep(2000);
               driver.manage().window().maximize();
               driver.get("https://www.facebook.com");
               String title= driver.getTitle();
               System.out.println(title);
               String url=driver.getCurrentUrl();
               System.out.println(url);
               String src=driver.getPageSource();
               System.out.println(src);
       }
}
Note:
    1. Get() method is used to enter the URL.
    2. It is mandatory to have internet connection to launch any URLs.
    3. Get() method waits until the page gets loaded, then only it will go till next statement.
   4. In Get() method it is mandatory to pass protocols, else it throws
      InvalidArguementException (Selenium RTE).
      For Example: https, http, etc
      For Example: Get(https://www.facebook.com);
HTML
   1. It is a Hyper Text Markup Language used by Developers to design Webpages (Web
      Application).
   2. In HTML we have predefined words which are enclosed with angular braces (< >).
   3. Anything enclosed with angular braces are called as HTML tags.
   4. Using HTML tags Developers will design elements like, text field, button, radio
      button, checkbox, etc.
   5. Elements which are placed inside webpage are called as web elements.
Parts of HTML
HTML
<html>
<head>
         <title> Testing Page </title>
</head>
<body>
USN <input type=”text”><br><br>
PSW<input type=”text”><br><br>
<input type=”button” value=”login”><br><br>
CB<input type=”checkbox”><br><br>
RB<input type=”Radio”>
</body>
</html>
Note:
   1. In order to write HTML code, we use Notepad of Editplus.
   2. HTML code should be saved with .html extension
   3. The only way to access HTML code is browser.
        Element Name                     Tag Name                       Attribute
            TextField                      input                       type=”text”
               Link                          a                          href=”url”
          Radio Button                     input                      type=”radio”
           Checkbox                        input                    type=”checkbox”
           Dropdown                       Select                             Id
              Table                        Table                         id, name
             Image                          img                         src=”path”
             Frame                        iframe                        src=”path”
Locators
   1. In Selenium before performing any actions such as click, clear or pass data, first we
      have to find the element or locate the element or inspect the element, this is called
      Locators.
   2. In Selenium, Locators are classified into 8 types, which are Static methods that
      belongs to “By” class and it is an Abstract class.
   3. Based on the performance wise Locators are classified as:
      a. tagName()
      b. id()
      c. name()
      d. className()
      e. linkText()
      f. partialLinktext()
      g. cssSelectors()
      h. X-path() ***Important***
Write a script to perform click action on a link by using
tagName() Location
System.setProperty("webdriver.chrome.driver","./Softwares/chromedriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get(“url”);
Thread.sleep(2000);
WebElement ele= driver.findElement(By.tagName(“a”));
Ele.click();
//or
driver.findElement(By.tagName(“a”)).click();
Sample HTML Source Code
<html>
<body>
<a id=”a1” name=”n1” class=”c1” href=www.facebook.com>facebook</a><br>
</body>
</html>
Characteristics of findElement
    1. It is used to handle single element.
    2. Return type of findElement() method is WebElement and it is an Interface.
    3. If a locator is matching with multiple elements, then findElement() method will
       return the address of first matching element.
    4. If an element is not found then it throws NoSuchElementsException (Selenium RTE).
Explain Below Statement
driver.findElement(By.tagName(“a”)).click();
In the browser find the element by Tag name as “a” and perform click action on it.
Write a script to
driver.findElement(By.id(“a1”)).click();
In the browser find the element by Id as “a1” and perform click action on it.
Write a script to
driver.findElement(By.name(“n1”)).click();
In the browser find the element by name as “n1” and perform click action on it.
Write a script to
driver.findElement(By.className(“c1”)).click();
In the browser find the element by className as c1 and perform click action on it.
Write a script to pass the data into the text field by using tagName
Locator
In Selenium we use sendKeys method to pass the data and it takes sequence of characters as
a parameter.
Source Code
UN: <input id=”a1” name=”n1” class=”c1” type=”text”;
driver.findElement(By.tagName(“input”)).sendKeys(“selenium”);
Explanation: In the browser we use find the element by tagName as “input” and pass the
data by using sendKeys as “Selenium”.
Write a script to pass the data into the text field by using Id Locator
Source Code
driver.findElement(By.id(“input”)).sendKeys(“selenium”);
Explanation:
Write a to clear the default data in a text field by using tagName
locator
In Selenium we use clear method to remove the data from the text field.
Source Code
UN: <input id=”a1” name=”n1” class=”c1” type=”text” value=”admin”;
driver.findElement(By.tagName(“input”)).clear();
Explanation: In the browser we use find the element by tagName as “input” and clear the
data.
driver.findElement(By.id(“a1”)).clear();
Explanation: In the browser we use find the element by Id as “a1” and clear the data.
Driver.findElement(By.name(“n1”)).clear();
Explanation: In the browser we use find the element by name as “n1” and clear the data.
Driver.findElement(By.class(“c1”)).clear();
Explanation: In the browser we use find the element by name as “c1” and clear the data.
Write a script to login to facebook by giving input
Write a script to login to youtube by giving input
Write a script to login to instagram by giving input
Locator No 2 – CSS Locator (Cascading Style Sheets)
   1. CssSelector is a expression and locator.
   2. It is used to specify color, height, width, font size of the web elements.
   3. Syntax of CssSelector:
      Syntax – tag[AN=’AV’]
                AN – Attribute Name
                AV – Attribute Value
To verify the CssExpressions we use validators in browsers such as:
   1. Firefox Browser – Try X-path, X-path finder, etc.
   2. Chrome Browser – Developer tool bar, Chrome-path, etc
Steps to download try xpath in firefox browser
   1. Open Firefox browser.
   2. Click on Alt.
   3. Click on Tools.
   4. Click on Addons.
   5. Click on Extension.
   6. Search for try X-path.
   7. Click on try xpath.
   8. Click on Add to Firefox.
   9. Click on Add.
   10. Click on Ok.
Steps to verify CssExpression by using try xpath
   1.   Open the respective page in Firefox browser.
   2.   Click on try xpath.
   3.   Select QuerySelector in Dropdown.
   4.   Type the CssExpression.
   5.   Click on Enter.
   6.   As soon as we click on enter it will display following options:
        i)      It will highlight the matching elements.
        ii)     It will display the number of matching elements. (Count)
Steps to verify CssExpression by using Developer Tool Bar
   1. Open the respective page in Chrome browser.
   2. Right click on element and inspect.
   3. Click on Control+F or Right click on the element and click on Inspect.
   4. Type the CssExpression.
   5. Click on Enter.
   6. As soon as we write the expression it will display the following options:
      i)      It will highlight the matching source code.
      ii)     It will display the number of matching elements. (Count)
   7. But, it will not highlight the matching element. Manually we need to move the
      mouse cursor on source code then it will highlight the matching element.
Note:
       The CssSelector provides shortcut for 2 locators, that is., ID and Class.
       In Css ‘#’ represent ID and ‘.’ represents Class.
       Ex 1: a[id=’a1’] -> a#a1
       Ex 2: a[class=’c1’] -> a.c1
X-Path
It is the path of an element in HTML tree structure.
               Html
                       Body
                               a-> element
X-path expression: html/body/a
X-path is classified into two types:
   1. Absolute X-path or X-path by position.
   2. Relate X-path or X-path by attributes.
Absolute X-path also called as X-path by value
In Absolute X-path we use single forward slash (/) to navigate from parent to immediate
child.
HTML Source Code
<html>
<body>
<div>
<input type=”text” value=A>
<input type=”text” value=B>
</div>
<div>
<input type=”text” value=C>
<input type=”text” value=D>
</div>
</body>
</html>
HTML Tree Structure
      html
             Body
                         Div
                               Input A
                               Input B
                         Div
                               Input C 4
                               Input D
 Element                                   Absolute X-path
 A                                         Html/Body/Div[1]/Input[1]
 B                                         Html/Body/Div[1]/Input[2]
 C                                         Html/Body/Div[2]/Input[1]
 D                                         Html/Body/Div[2]/Input[2]
 AB                                        Html/Body/Div[1]/Input
 CD                                              Html/Body/Div[2]/Input
 AC                                              Html/Body/Div/Input[1]
 BD                                              Html/Body/Div/Input[2]
 AD                                              Html/Body/Div[1]/Input[1]|
                                                 Html/Body/Div[2]/Input[2]
 BC                                              Html/Body/Div[1]/Input[2]|
                                                 Html/Body/Div[2]/Input[1]
 ABD                                             Html/Body/Div[1]/Input|
                                                 Html/Body/Div[2]/Input[2]
 BAC                                             Html/Body/Div[1]/Input[2]|
                                                 Html/Body/Div/Input[1]
Note:
        In X-path indexing starts from 1.
        If the Tag name repeats under the same parent, then increment the index by 1.
        In order to merge multiple X-paths we use Pipeline operator (|).
        To merge n number of X-paths we use n-1 number of times Pipeline operators.
Relative X-path also called as X-path by Attributes
     1. In order to reduce the length of Absolute X-path we go for Relative X-path.
     2. The relative way of writing the X-path is most preferable.
     3. In relative X-path, we use double forward slash (//) to navigate from parent to any of
        the child.
 Element                                         Relative X-path
 A                                               //Div[1]/Input[1]
 B                                               //Div[1]/Input[2]
 C                                               //Div[2]/Input[1]
 D                                               //Div[2]/Input[2]
 AB                                              //Div[1]/Input
 CD                                              //Div[2]/Input
 AC                                              //Input[1]
 BD                                              //Input[2]
 AD                                              //Div[1]/Input[1]|
                                                 ///Div[2]/Input[2]
 BC                                              //Div[1]/Input[2]|
                                                 //Div[2]/Input[1]
 ABD                                             //Div[1]/Input|
                                                 //Div[2]/Input[2]
 BAC                                             //Div[1]/Input[2]|
                                                      //Input[1]
 ABCD                                                 //Input
Write an X-path to inspect
All Links - //a
All Images - //img
All Links and Images - //a|//img
All Input Tags - //input
Every Element - //*
Difference between //a and //a[1]
//a – It highlights all the matching links
//a[1] – It highlights all the first matching links
Difference between / and //
/ - Navigates from parent to immediate child.
// - Navigates from parent to any child.
X-path by attributes
In X-path we can specify the attributes and relative way of writing the X-path is preferable.
Syntax: //tag[@AN=’AV’]
        @ -> It searches for the element in all the directions.
Write an X-path to inspect ‘Next’ button in Yahoo page
//input[@id=’login.signin’]
Write an X-path to inspect ‘Search’ text field in Youtube
page
//input[@placeholder=’Search’]
Write an X-path to inspect ‘Create Account’ element in
Yahoo page
//a[@id=’createacc’]
Write an X-path by using multiple attributes
Login to FB and play youtube video assignment
ABSENT NOTES TO BE WRITTEN
X-path by using contains()
In X-path we can use contains() (function) to handle partially dynamic elements.
Contains method in X-path is similar to contains() in Java language. Here, we catch hold of
the element which is static and try to handle dynamic element.
Note: The main agenda to use contains() is to handle partially dynamic elements.
Syntax: //tag[contains(text(),’TV’)];
Inspect Google link in a dummy page
<a id=”a1” href=”url”>google </a>
//a[contains(text(),’google 2024’)];
Inspect Servlet version in attoive application
<td> Servlet API Version: 2.5 </td>
//td[contains(.,’Servlet A Version’)];
Inspect patch level in aptitime application
<td> Patch level:20.0 </td>
//td[contains(.,’Patch level’)];
Handling Completely Dynamic Elements
    1. To handle completely dynamic elements we use independent dependent X-path or X-
       path by traversing (navigating from one element to another).
    2. X-path by transversing is classified into 2 types:
       a. Forward Traversing
       b. Backward Traversing
Forward Traversing – Navigating from parent to immediate child or any child by using / or //
is called as Forward Traversing.
Backward Traversing – Navigating from child to immediate parent by using //.. is called as
Backward Traversing.
Steps To Inspect Completely Dynamic Elements
   1. Inspect the Static element.
   2. Navigate from the Static element to the Parent element.
   3. Navigate from the Parent element to the Dynamic child.
Sample HTML Source Code
<html>
<body>
<table border =1>
<tbody>
<tr>
<td>1</td>
<td>Martin</td>
<td>50</td>
</tr>
<tr>
<td>2</td>
<td>KGF</td>
<td>200</td>
</tr>
<tr>
<td>3</td>
<td>Kantara</td>
<td>220</td>
</tr>
</tbody>
</body
</html>
Inspect Martin movie collection in a dynamic page
DRAW DIAGRAM
//td[text(),’Martin’]//../td[3]
In the above example Martin is a Static element (Independent) and Movie Collection is a
Dynamic element.
Inspect Stable version by keeping Python as Static in
Selenium page
//p[text(),’Python’]//../p[2]
Inspect API docs by keeping JavaScript as a Static in
Selenium page
//p[.,’JavaScript’//../p[4]
Siblings Function
     1. Navigating from one child to another child element is called as Siblings in X-path.
     1. In X-path Siblings are classified into 2 types:
        a. Following Sibling
        b. Preceding Sibling
Following Sibling – It highlights the elements which are downwards in the HTML
tree structure or towards the right side in a webpage.
Syntax: Static Xpath/following-sibling::tag
:: -> Scope Resolution Operator
Inspect Martin Movie Collection in a Dummy Page
tr
       td      A
       td      1
       td      Martin
       td      50
       td      B
//td[text(),=’Martin’]/following-sibling::td[1]
Inspect element p by keeping a as Static in a Dummy page
//td[text(),=’A’]/following-sibling::td[4]
Inspect API docs by keeping Python as Static in Selenium page
//p[text()=’Python’]/following-sibling::p[3]
Preceding Sibling - It highlights the elements which are upwards in the HTML tree
structure or towards the left side in a webpage.
Syntax: Static Xpath/preceding-sibling::tag
Inspect element A by keeping Martin as Static in a Dummy page
//td[text()=’Martin’]/preceding-sibling::td[2]
Inspect Stable version of .NET language by keeping API docs as Static
//a[text()=’API Docs’]/../preceding-sibling::p[2]
Ancestor Tag
It is used to navigate from Child to any of its Parent.
Syntax: Xpath/ancestor::tag
Html
         Body
                Div
                      A
Syntax: //a/ancestor::Body
Note:
/ -> Navigate from Parent to immediate Child.
// -> Navigate from Parent to any Child.
/.. -> Navigate from Child to immediate Parent.
Siblings -> Navigate from one Child to another Child.
Ancestor -> Navigate from Child to any Parent.
Write X-paths for below mentioned tree structure
tbody
         tr
                td    1
                td    A
                td    66
         tr
                td    2
                td    B
                td    99
         tr
                td    3
                td    C
                td    33
 1->A                                        //td[text()=’1’]/following-sibling::td[1]
 3->33                                       //td[text()=’3’]/following-sibling::td[2]
 99->2                                       //td[.=’99’]/preceding-sibling::td[2]
66->A                                      //td[.=’66’]/preceding-sibling::td[1]
A->B                                       //td[.=’A’]/../following-sibling::tr[1]/td[2]
1->99                                      //td[.=’1’]/../following-sibling::tr[1]/td[3]
C->1                                       //td[.=’C’]/../preceding-sibling::tr[2]/td[1]
33->99                                     //td[.=’33’]/../preceding-sibling::tr[1]/td[3]
C->B->A                                    //td[.=’C’]/../preceding-sibling::tr[1]/td[2]/../
                                                            preceding-
                                                            sibling::tr[1]/td[2]
66->99->33                                 //td[.=’66’]/../following-sibling::tr[1]/td[3]/../
                                                            following-sibling::tr[1]/td[3]
B->A->3                                    //td[.=’B’]/../preceding-sibling::tr[1]/td[2]/../
                                                            following-sibling::tr[2]/td[1]
A->99->66->3                               //td[.=’A’/../following-sibling::tr[1]/td[3]/../
                                                            preceding-sibling::tr[1]/
                                                            td[3]/../tr[2]/td[1]
X-path by Grouped Index
  1. In real time, if we are not able to locate the element by using attributes, multiple
     attributes, text, contains, etc. Then we go for X-path by Grouped Index.
  2. Here, the main agenda is to locate the element and get the count as 1.
  3. In X-path we use grouped index to achieve it.
  4. Syntax: (Xpath)[index]
     – Here, we specify the X-path inside the parenthesis and specify the index inside the
     square brackets.
     Xpath – Priority 1
     Index – Priority 2
HTML Tree Structure
Html
       Body
               Div
                     Input A
                     Input B
               Div
                       Input C
                       Input D
//input -> 4 (ABCD)
//input[1] -> 2 (AC)
//input[2] -> 2(BD)
                             A          A            B
                             B          C            D
Ex1: (//input)[2]            C
Ex2: (//input[1])[1]         D
Ex3: (//input[2])[2]
In the above examples, as soon as we specify the parenthesis all the matching elements will
get dumped inside X-path array and based on the index specified it will highlight the
matching element.
Write an X-path to inspect men’s t-shirt in Flipkart page
(//div[text()=’Rs.149’)[3]
Sample HTML Source Code
<html>
<body>
<input type="checkbox">1</input><br>
<input type="checkbox">2</input><br>
<input type="checkbox">3</input><br>
<input type="checkbox">4</input><br>
<input type="checkbox">5</input><br>
<input type="checkbox">6</input><br>
<input type="checkbox">7</input><br>
<input type="checkbox">8</input><br>
<input type="checkbox">9</input><br>
<input type="checkbox">10</input><br>
</body>
</html>
 X-path                                                      Matching Elements
 (//input[1])                                                1(1)
 (//input[5])                                                1(5)
 (//input[9])                                                1(9)
 (//input[last()])                                           1(10)
 (//input[last()-1])                                         1(9)
 (//input[last()+1])                                         No Such Element
 (//input[last()>3])                                         7(4,5,6,7,8,9,10)
 (//input)[position()>=3]
 (//input)[position()>3 and position()<last()]
 (//input)[position()>last()]                                9(1,2,3,4,5,6,7,8,9)
 (//input)[position() mod 2=0]
 (//input)[position() mod 2=1]                               5(1,3,5,7,9)
 (//input[3]|//input[5]|//input[9])                          3(3,5,9)
Difference between CSS selector and X-path
(***Important***)
 CSS Selector                                     X-path
 We cannot use multiple attributes                We can use multiple attributes
 It doesn’t search for element in all direction   It searches for element in all direction
 Here . represents class                          Here . represents text()
 We cannot handle dynamic elements                We can handle dynamic elements
 It is faster                                     It is slower compared to CSS
WebElement
   1. WebElement is an Interface which consists of 17 abstract methods.
   2. All the methods of WebElement are used to perform action on elements inside the
      webpage. The actions include click, clear, sendkeys, etc.
Methods of WebElement Interface
                             WebElement                         Return Type
               Clear()                                 void
               Click()                                 void
               findElement(By arg0)                    WebElement
               findElements(By arg0)                   List<WebElement>
               getAttribute(String arg0)               String
               getCssValue(String arg0)                String
               getLocation()                           Point
               getRect()                               Rectangle
               getScreenshotAs(OutputType<X> arg0)     X
               getSize()                               Dimension
               getTagName()                            String
               getText()                               String
               isDisplayed()                           boolean
               isEnabled()                             boolean
               isSelected()                            boolean
               sendKeys(ChatSequence.. arg0)           void
               Submit()                                void
Write a script to verify whether an element is present in the
webpage or not
driver.get("http://www.facebook.com");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.id("Email"));
boolean b = ele.isDisplayed();
if(b)
       {
              System.out.println("is displayed");
       }
       else
       {
              System.out.println("not displayed");
        }
Write a script to verify whether the element is enabled or not
WebElement ele = driver.findElement(By.xpath("//li(text(),'Disabled')")).click();
        boolean b = ele.isEnabled()
        if(b)
        {
                System.out.println("is enabled");
        }
        else
        {
                System.out.println("not enabled");
        }
Write a script to verify whether the element is selected or not
Driver.get(“URL”);
Thread.sleep(2000);
WebElement ele = driver.findelement(by.id(“domain1”));
Boolean b=ele.isSelected();
If(b)
{
Sysout(“Element selected”);
}
Else
{
Sysout(“element not selected”)
}
Handling keyboard functionalities
   1.    In Selenium to handle the keyboard we use Keys.
   2.    Keys is inherited from Enum and it also an example for Enum.
   3.    All the member inside keys are public static final variables.
   4.    In Eclipse final members are represented in dark blue color.
Write a script to clear the data from text field by using Keys
<html>
<body>
<input type =”text” id=”a1” value= “hello”>
</body>
</html>
Driver.get(“URL”);
Thread.sleep(2000);
webElement ele=driver.findElement(By.id(“a1”));
ele.sendKeys(Keys.CONTROL+”a”);//select all
Thread.sleep(2000);
Ele.sendKeys(Keys.DELETE);//deletes data
Write a script to click on a link by using keyboard in Facebook
Driver.get(“URL”);
Thread.sleep(2000);
webElement ele=driver.findElement(By.xpath(“//a[text()=’Forgotten Password”]));
ele.sendKeys(Keys.ENTER);
WebElement ele = driver.findElement(By.xpath("//input[@value='Manual']"));
                ele.sendKeys(Keys.CONTROL+"ax");
                WebElement dle = driver.findElement(By.xpath("//input[@value=' ']"));
                dle.sendKeys(Keys.CONTROL+"v");
               WebElement ele =
driver.findElement(By.xpath("//input[@value='Automation']"));
                ele.sendKeys(Keys.CONTROL+"ax");
                WebElement dle = driver.findElement(By.xpath("//input[@value=' ']"));
                dle.sendKeys(Keys.CONTROL+"v");
Write a script to fetch text of an element in a webpage
driver.get("https://www.facebook.com/");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.xpath("//a [@title='Kannada']"));
String h = ele.getText();
System.out.println(h);
Thread.sleep(2000);
Write a script to fetch the attribute value of an element in a
webpage
Driver.get(https://www.facebook.com/);
Thread.sleep(1500);
WebElement ele=driver.findElement(By.xpath(“//a[text()=’ ;))”]’اردو
String title = ele.getAttribute(“title”);
System.out.println(title);
Write a script to fetch the location of an element in a webpage
Driver.get(https://www.facebook.com/);
Thread.sleep(1500);
WebElement ele=driver.findElement(By.xpath(“//a[text()=’ ;))”]’اردو
Point p = ele.getLocation();
System.out.println(p);
System.out.println(p.getX());
System.out.println(p.getY());
Write a script to fetch the font size of an element in a webpage
Note: In order to fetch the height, color, size, width, etc., we use getCssValue method and
parameterized with the value needed.
driver.get("https://www.facebook.com/");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.id("email"));
String fSize = ele.getCssValue("font-size");
System.out.println(fSize);
Write a script to fetch the height and width of an element in a
webpage
WebElement ele = driver.findElement(By.id("email"));
int h = ele.getSize().getHeight();
System.out.println(h);
int w = ele.getSize().getWidth();
System.out.println();
Write a script to enter the URL without using Get method
driver.navigate().to("https://www.google.com");
Write a script to perform backward, forward and refresh action
driver.navigate().to("https://www.google.com");
driver.navigate().to("https://www.facebook.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
Difference between Navigate() and Get()
Get() - We cannot perform backward, forward and refresh action also cookies are not stored.
Navigate() - We can perform backward, forward and refresh action, also the cookies are
stored.
Write a script to resize the browser
Note: In Selenium we use dimension class to resize the browser.
Dimension d=new Dimension(200, 300);
driver.manage().window().setSize(d);
Write a script to drag the browser
Note: In Selenium to drag the browser we use Point class.
Point p=new Point(200, 300);
driver.manage().window().setPosition(p);
Write a script to delete the history in the browser
driver.manage().deleteAllCookies();
Handling Multiple Elements
        To handle multiple elements, we use findElements() (method).
        Return type of findElements() is List<WebElement>.
         Note: List is an Interface and also one among the Collections concept.
                        List<WebElement> -> Return Type
                        <WebElement> -> Datatype
        If a Locator is matching with multiple elements, then findElements() will return the
         address of all matching elements.
        If an element is not found then it displays EmptyArrayList or EmptyList.
Write a script to fetch the address of all the links in a Dummy
page
<html>
<body>
<a id=”a1” href=”url”>google</a><br>
<a id=”a2” href=”url”>Facebook</a>
</body>
</html>
driver.get("URL");
List<WebElement> links = driver.findElements(By.xpath("//a"));
int count = links.size();
System.out.println(count);
Write a script to fetch the count of all the links in Amazon
application
driver.get("https://www.amazon.in");
List<WebElement> links = driver.findElements(By.xpath("//a"));
int count = links.size();
System.out.println(count);
Write a script to fetch the count of all the links and images in
Flipkart application
driver.get("https://www.flipkart.com");
List<WebElement> links = driver.findElements(By.xpath("//a|//img"));
int count = links.size();
System.out.println(count);
Write a script to fetch the text of all the links in Amazon
application
driver.get("www.amazon.in");
List<WebElement> links = driver.findElements(By.xpath("//a"));
int count = links.size();
for(int i=0; i<count; i++)
{
        WebElement we = links.get(i);
        String t = we.getText();
        System.out.println(t);
}
************Other way*************
driver.get("https://www.amazon.in");
List<WebElement> links = driver.findElements(By.xpath("//a"));
for (WebElement we : links)
{
System.out.println(we.getText());
}
Write a script to print the same in reverse order
for(int i=count-1; i>=0; i--)
        {
                WebElement we = links.get(i);
                String t = we.getText();
                System.out.println(t);
        }
Write a script check and uncheck the checkboxes
driver.get("file:///D:/QSpiders/Selenium/Checkboxes.html");
Thread.sleep(1500);
List<WebElement> inpt = driver.findElements(By.xpath("//input"));
int count = inpt.size();
for(int i=0; i<count; i++)
{
        WebElement in = inpt.get(i);
        in.click();
}
for(int i=count-1; i>=0; i--)
{
        WebElement we = inpt.get(i);
        we.click();
}
For Each Loop or Enhanced For Loop
It is a concept in Java which is used to convert the array or collection type member into a
datatype.
Syntax: for(Datatype VN: Array/Collection)
        {
        -----
        -----
        }
Example: int a[] = {1 2 3}; ----> [1 2 3]
            for(int b: a)
            {
                 Syso(b); --> 1 2 3
            }
Write a script to print the href value of all the links in Amazon
using For Each Loop
Note: Before Opting For Each Loop there are certain limitations for it.
        1.   We cannot print the elements in reverse order.
        2.   We cannot print alternative elements.
        3.   We cannot specify any conditions.
        4.   It supports only array or collection type.
        5.   Performance wise For Each Loop is faster compared for For Loop.
        Example: driver.get("url");
                       List<webElements> links = driver.findElements(By.xpath("//a"));
                       for (WebElement we : links)
                       {
                               System.out.println(we.getAttribute("href"));
                       }
Write a script to print the source value of all the images in an
application
driver.get("url");
List<webElements> links = driver.findElements(By.xpath("//img"));
for (WebElement we : links)
{
        System.out.println(we.getAttribute("src"));
}
Difference between findElement() and findElements()
 findElement()                            findElements()
 It is use to handle single element.      It is used to handle multiple elements.
 Return is WebElement                     Return type is List<WebElement>
 It returns the address of first matching It returns the address of all the matching
 element.                                 elements.
 If an element is not found it throws     If an element is not present is displays
 NoSuchElementException.                  EmptyArrayList or EmptyList.
Handling Dropdowns / List Box / Menu Bar
      To develop the dropdowns, the developers use select tag (<Select>). These
       dropdowns are classified into two types.
    1. Single Select Dropdown
    2. Multi Select Dropdown
       Single Select Dropdown
       Here, we can select only one option and we cannot perform deselect action.
       Multi Select Dropdown
       Here, we can select multiple options and we can perform deselect action.
      In Selenium there are no in-built methods from WebElement interface to handle it.
      In Selenium we use Select class to handle the dropdowns.
      Select class is a concrete class which consists of parameterized constructor and it
       takes one parameter as an input, ie., address of a dropdown.
      Select class is imported from “ui” package.
Single Select Dropdown
<html>
<body>
<select id = “Nandanas” single>
<option value = “i”> Mutton Biryani </option>
<option value = “j”> Chicken Biryani </option>
<option value = “k”> Egg Biryani </option>
<option value = “l”> Veg Biryani </option>
<option value = “m”> Masala Dosa </option>
<option value = “n”> Chitranna </option>
</select>
</body>
</html>
Multi Select Dropdown
<html>
<body>
<select id = “Nandanas” multiple>
<option value = “i”> Mutton Biryani </option>
<option value = “j”> Chicken Biryani </option>
<option value = “k”> Egg Biryani </option>
<option value = “l”> Veg Biryani </option>
<option value = “m”> Masala Dosa </option>
<option value = “n”> Chitranna </option>
</select>
</body>
</html>
Methods of Select Class
deselectAll()
deselectByIndex(int index)
deselectByValue(String arg0)
deselctByVisibleText(String arg0)
getAllSelectedOptions()
getFirstSelectedOption()
getOptions()
getWrappedElement()
isMultiple()
selectByIndex(int index)
selectByValue(String arg0)
selectByVisibleText(String arg0)
Write a script to select multiple options from a dropdown and de-
select it
driver.get("url");
WebElement ele = driver.findElement(By.id("Nandanas"));
Select s = new Select(ele);
s.selectByIndex(1);
s.selectByValue("l");
s.selectByVisibleText("Chitranna");
s.deselectAll();
Write a script to verify whether the dropdown is multiselect or
not
WebElement ele = driver.findElement(By.id("Nandanas"));
Select s = new Select(ele);
boolean b = s.isMultiple();
if(b)
{
        System.out.println("multiselect dd");
}
else
{
                System.out.println("not a multiselect");
}
Write a script to fetch the count of no of years and months in
Facebook page
driver.get("https://www.facebook.com/r.php");
WebElement ele = driver.findElement(By.id("year")); //For Year
WebElement ele = driver.findElement(By.id("month")); // For Month (2 Separate Programs)
Select s = new Select(ele);
List<WebElement> opt = s.getOptions();
System.out.println(opt.size());
Write a script to fetch the text of all the options in the dropdown
driver.get("https://www.facebook.com/r.php");
WebElement ele = driver.findElement(By.id("year"));
String text = ele.getText();
Select s = new Select(ele);
List<WebElement> opt = s.getOptions();
for (WebElement we : opt)
{
        System.out.println(we.getText());
}
Write a script to sort all the options in Ascending Order by using
Array List
driver.get("https://www.facebook.com/r.php");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
        ArrayList<String> a = new ArrayList<String>();
        List<WebElement> opt = s.getOptions();
        for (WebElement we : opt)
        {
                  String text = we.getText();
                  a.add(text);
        }
                  Collections.sort(a);
                  for(String l1 : a)
        {
                  System.out.println(l1);
        }
     @a1                                Jan                    Jan             April
     @a2                                Feb                    Feb             Aug
                                       March               March
s.getOptions();                  we.getText();           T.add(text);   Collections.sort();
                                                         Elements get   Sorted Elements
                                                          added in an
                                                             array
        Write a script to sort all the
        options in Ascending Order by using Tree Set
        driver.get("https://www.facebook.com/r.php");
        Thread.sleep(1500);
        WebElement ele = driver.findElement(By.id("month"));
        Select s = new Select(ele);
        TreeSet<String> T = new TreeSet<String>();
        List<WebElement> opt = s.getOptions();
        for (WebElement we : opt)
{
        String text = we.getText();
        T.add(text);
}
for(String t1 : T)
{
        System.out.println(t1);
}
Write a script to sort elements in Reverse Order by using Array
List
driver.get("https://www.facebook.com/r.php");
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
List<WebElement> opt = s.getOptions();
ArrayList<String> a = new ArrayList<String>();
for (WebElement we : opt)
{
        String text = we.getText();
        a.add(text);
}
Collections.sort(a,Collections.reverseOrder());
for(String a1:a)
{
        System.out.println(a1);
}
Write a script to sort elements in Reverse Order by using Tree Set
driver.get("https://www.facebook.com/r.php");
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
List<WebElement> opt = s.getOptions();
TreeSet<String> t=new TreeSet<String>(Collections.reverseOrder());
for (WebElement we : opt)
{
        String text = we.getText();
        a.add(text);
}
for(String a1:a)
{
        System.out.println(a1);
}
Type Casting from Array List to TreeSet
Arraylist<String> l = new Arraylist<String>();
TreeSet<String> t= new TreeSet<String>(l);
Program on Type Casting from Array List to TreeSet
driver.get("https://www.facebook.com/r.php");
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
ArrayList<String> a = new ArrayList<String>();
List<WebElement> opt = s.getOptions();
for (WebElement we : opt)
{
        String text = we.getText();
        a.add(text);
}
TreeSet<String> t = new TreeSet<String>(a);
for(String l1 : t)
{
        System.out.println(l1);
}
Type Casting from TreeSet to Array List
TreeSet<String> t= new TreeSet<String>();
Arraylist<String> l = new Arraylist<String>(t);
Program on Type Casting from TreeSet to Array List
driver.get("https://www.facebook.com/r.php");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
TreeSet<String> T = new TreeSet<String>();
List<WebElement> opt = s.getOptions();
for (WebElement we : opt)
{
        String text = we.getText();
        T.add(text);
}
ArrayList<String> a = new ArrayList<String>(T);
for(String l1 : a)
{
        System.out.println(l1);
}
Write a script to verify whether an option is present in the
dropdown or not
driver.get("https://www.facebook.com/r.php");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
List<WebElement> opt = s.getOptions();
ArrayList<String> a = new ArrayList<String>();
for (WebElement we : opt)
{
        String text = we.getText();
        a.add(text);
}
if (a.contains("Nov"))
{
        System.out.println("Month is Present");
}
else
{
        System.out.println("Month is Not Present");
}
Write a script to print the options excluding Nov month
driver.get("https://www.facebook.com/r.php");
Thread.sleep(1500);
WebElement ele = driver.findElement(By.id("month"));
Select s = new Select(ele);
List<WebElement> opt = s.getOptions();
ArrayList<String> a = new ArrayList<String>();
for (WebElement we : opt)
{
        String text = we.getText();
        a.add(text);
}
a.remove("Nov");
for(String l1 : a)
{
        System.out.println(l1);
}
Note: If we try to perform deselect action on a single select dropdown then it throws
UnsupportedOperationException (Java RTE).
***************PAGE LEFT FOR PREVIOUS TOPIC SIR SHOULD GIVE*****************
Handling Actions Class
      In real time to perform mouse hovering there are no methods present in webdriver
       or webelements interface.
      To perform actions such as mouse hovering, double click, right click, drag and drop,
       click and hold, etc., we use Actions class.
      Actions class is a concrete class, which consists of parameterized constructor and it
       takes one parameter as an input that is address of the application.
      Actions class is imported/inherited from interactions package.
   Note:      Select – Address of the element -> ui package
              Actions – Address of the application -> interactions package.
      Actions act = new Actions(driver);
Handling Mouse Hovering
In Selenium, to perform mouse hover actions, we use Actions class. Here, we invoke a
method called movetoElement and parameterize it with address of the element.
Here, once after sequentially invoking the methods. It is mandatory to call perform method
at the last.
Write a script to perform Mouse Hovering on fashion element in
Flipkart page
driver.get("https://www.flipkart.com/");
WebElement ele = driver.findElement(By.xpath("//span[text()='Fashion']"));
Actions act=new Actions(driver);
act.moveToElement(ele).perform();
Handling Drag and Drop Action
In Selenium, to perform drag and drop we use Actions class. Here, we invoke a method
called dragAndDrop and parameterize it with two arguments that is source and destination.
perform method is mandatory.
Write a script to perform Drag and Drop Action
driver.get("http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-
3.html#google_vignette");
WebElement src = driver.findElement(By.id("box3"));
WebElement dst = driver.findElement(By.id("box103"));
Actions act=new Actions(driver);
act.dragAndDrop(src, dst).perform();
Handling Double Click Action
In Selenium to perform double click action we use Actions class. Here, we invoke a method
called doubleClick and parameterize it with address of the element. perform method is
mandatory.
Write a script to perform Double Click Action
driver.get("https://demo.guru99.com/test/simple_context_menu.html");
WebElement dclick = driver.findElement(By.xpath("//button[text()='Double-Click Me To See
Alert']"));
Actions act=new Actions(driver);
act.doubleClick(dclick).perform();
Handling Right Click Action
In Selenium to perform right click action we use Actions class. Here, we invoke a method
called contextClick and parameterize it with address of the element. perform method is
mandatory.
Write a script to perform Right Click Action
driver.get("https://demo.guru99.com/test/simple_context_menu.html");
WebElement rclick = driver.findElement(By.xpath("//span[text()='right click me']"));
Actions act=new Actions(driver);
act.contextClick(rclick).perform();
Note: If you are unable to inspect element from right click on the element. Click on inspect
on any other element and then click on Toggle Device Toolbar (Ctrl+Shift+M).
Handling Click and Hold Action
In Selenium to perform click and hold action we use Actions class. Here, we invoke a method
called clickAndHold and parameterize it with address of the element. perform method is
mandatory.
Write a script to perform Click and Hold Action
driver.get("https://demoapps.qspiders.com/ui/clickHold?sublist=0");
WebElement candh = driver.findElement(By.id("circle"));
Actions act = new Actions(driver);
act.clickAndHold(candh).perform();
 Actions                                        Methods
 Mouse Hovering Action                          moveToElement()
 Drag and Drop                                  dragAndDrop(source,destination)
 Double Click                                   doubleClick()
 Right Click                                    contextClick()
 Click and Hold                                 clickAndHold()
Robot Class
      Robot class from Java (AWT Package): It is an inbuilt class in Java which is inherited to
       Selenium. In order to access Robot class, we invoke AWT package (Abstract Window
       Toolkit).
      Actions related to the keyboard or cursor (mouse actions) AWT package can be used.
Why Robot Class?
      It is used in Selenium because for few test cases, the user should have control over
       the keyboard functionalities or mouse actions. In instances such as minimizing the
       browser, opening in new tab, handling download popups, etc.
      In Robot class, KeyEvent class is used for keyboard functionalities and also, we use
       keyPress or keyRelease to perform the actions.
      All the events inside the Robot class are performed virtually.
Write a script to right click on an element and open it in new tab
driver.get("https://www.google.com/");
WebElement rclick = driver.findElement(By.xpath("//a[text()='ಕನ್ನಡ']"));
Actions act = new Actions(driver);
act.contextClick(rclick).perform();
Robot r=new Robot();
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_T);
Write a script to minimize the browser, close the browser without
using quit or close
driver.get("https://www.google.com/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_N);
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_SPACE);
r.keyRelease(KeyEvent.VK_N);
driver.manage().window().maximize();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_F4);
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_F4);
****************ABSENT NOTES TO BE WRITTEN*******************
Write a program to and to replace all current jd
Generic script to capture the photo
   To call the Generic methods, to capture the photo, we have to invoke class name
    followed by method name.
   All the failed testcases photos will be stored in photos folder inside the IDE.
   We store the photos based on the date and time. Ie., the latest photo pops-ups at
    the top.
JavaScriptExecuter
      In Selenium to handle disabled elements and also to perform scroll action, we use
       JavaScriptExecuter (JSE).
      JSE is an Interface, which consists of 2 Abstract Methods.
      In order to access these methods, we explicitly type caste from Webdriver to JSE.
      JavaScriptExecuter jse = (JavaScriptExecuter) driver;
   ***********Insert Diagram*********************
Methods of JSE
   1. executeAsyncScript(String arg0, Object
   2. executeScript
Source Code
<html>
<body>
UN: <input type="text" id="a1" value="admin" disabled>
</body>
</html>
Write a script to handle disabled element and pass the data
driver.get("file:///C:/Users/Ashrith%20R/OneDrive/Documents/QSpiders/Selenium/
HandlingDisabledElementUsingJSE.html");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('a1').value='hello'");
Write a script to handle disabled element and clear the data
driver.get("file:///C:/Users/Ashrith%20R/OneDrive/Documents/QSpiders/Selenium/
HandlingDisabledElementUsingJSE.html");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('a1').value=' '");
Note: Document is a class, which is partially implemented and value is a method which is
used to pass or clear the data and it overrides pre-existing data.
Write a script to perform scroll action thrice downwards and
upwards in a webpage
driver.get("https://www.amazon.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
for(int i=0;i<3;i++)
{
        js.executeScript("window.scrollBy(0,500)");
        Thread.sleep(1500);
}
for(int j=0;j<3;j++)
{
        js.executeScript("window.scrollBy(0,-500)");
        Thread.sleep(1500);
}
Write a script to scroll down to the specific element and perform
the action
driver.get("https://www.amazon.com");
WebElement ele = driver.findElement(By.xpath("//a[text()='Sell apps on Amazon']"));
Point p = ele.getLocation();
int x= p.getX();
int y= p.getY();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy("+x+","+y+")");
Note: The output is of string type, since we are fetching the location of x and y and storing it
in a variable, we have to convert the variable to a string type, so we are using double quotes.
Advantages of JSE
    1. It is used to handle disabled element.
    2. It is used to perform scroll action.
    3. It is used to pass and clear the data, without using sendKeys() or clear().
Handling Child Browser Popup
It is a browser which is resized to look like a popup.
Characteristics:
       We can minimize, maximize and close the popup. Also, here we can inspect and drag
        it.
       To handle Child Browser Popup, we use two methods. That is.,
            1) getWindowHandle()
            2) getWindowHandles()
getWindowHandle() – with the return type as String. It is used to fetch the address of only
the parent browser.
getWindowHandles() – with the return type as Set<String> (Set of String). It is used to fetch
the address of both parent and child browser.
       In order to switch from one tab to another or one window to another, we use
        driver.switchTo().window() and parameterize it with address of the browser.
Write a script to fetch the address of only the parent browser
driver.get("https://www.google.com/");
String l = driver.getWindowHandle();
System.out.println(l);
Write a script to print the count of browsers and also their
addresses
driver.get("https://skpatro.github.io/demo/links/");
driver.findElement(By.name("NewWindow")).click();
Set<String> alwh = driver.getWindowHandles();
System.out.println(alwh.size());
for (String wh : alwh)
{
       System.out.println(wh);
}
Write a script to fetch the title of all the browsers and close it
driver.get("https://skpatro.github.io/demo/links/");
driver.findElement(By.name("NewWindow")).click();
Set<String> alwh = driver.getWindowHandles();
System.out.println(alwh.size());
for (String wh : alwh)
{
       driver.switchTo().window(wh);
       System.out.println(driver.getTitle());
       Thread.sleep(1500);
       driver.close();
}
Write a script to close only the parent browser
driver.get("https://skpatro.github.io/demo/links/");
driver.findElement(By.name("NewWindow")).click();
Thread.sleep(1500);
String p_id = driver.getWindowHandle();
Set<String> alwh = driver.getWindowHandles();
System.out.println(alwh.size());
for (String wh : alwh)
{
       driver.switchTo().window(wh);
       System.out.println(driver.getTitle());
       Thread.sleep(1500);
       if(wh.equals(p_id))
       {
               driver.close();
       }
}
Write a script to close only the child browsers
driver.get("https://skpatro.github.io/demo/links/");
driver.findElement(By.name("NewWindow")).click();
Thread.sleep(1500);
String p_id = driver.getWindowHandle();
Set<String> alwh = driver.getWindowHandles();
System.out.println(alwh.size());
alwh.remove(p_id);
System.out.println(alwh.size());
for (String wh : alwh)
{
       driver.switchTo().window(wh);
       driver.close();
}
Write a script to close the dedicated tab
driver.get("https://skpatro.github.io/demo/links/");
driver.findElement(By.name("NewWindow")).click();
Thread.sleep(1500);
String p_id = driver.getWindowHandle();
Set<String> alwh = driver.getWindowHandles();
System.out.println(alwh.size());
alwh.remove(p_id);
System.out.println(alwh.size());
for (String wh : alwh)
{
        driver.switchTo().window(wh);
        String title = driver.getTitle();
        if(title.equals("Browser Windows"))
        {
                driver.close();
        }
}
***********Absent Notes**************
Pop-ups
It is a Pop-up that we get usually when we try to fill webforms. Initially the control will be on
the page (Sign up) and once after we click on submit the control will switch from page to
Pop-up. To switch the Selenium control to the Pop-up we use alert interface. Here, we use
the statement called driver.switchTo().alert().
Characteristics
  1. We can’t drag the Pop-up.
  2. We cannot inspect the Pop-up.
Note:
       In order to fetch the message printed on the Pop-up we use getText(), inherited from
        alert interface.
       To click on ok or anything similar we use accept method.
       To click on cancel or anything similar we use dismiss().
Write a script to handle alert and confirmation pop-up
Note:
       Since the developers use JavaScript language to develop this popup it is also called as
        JavaScript popup.
       If we try to implement Alert methods when there is no Alert popup, then it throws
        NoAlertPresentException (Selenium RTE).
Hidden Division Pop-up
Initially the pop-up will be hidden. Once after you click on the element, it will display the
pop-up, so that name Hidden. also, the developers use <div> (div tag) to develop this popup
which refers to hidden division pop-up.
Characteristics
  1. We cannot drag the popup.
  2. We can inspect the popup.
Note:
       Since the elements can be inspected, we need not to use any separate classes or
        interface or methods to handle it.
       Instead findElement() will do the job.
Write a script to handle hidden division popup
driver.get("https://www.redbus.in/");
Thread.sleep(1500);
driver.findElement(By.xpath("//span[.='Date']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//span[.='21']")).click();
File Upload Pop-up
In real time when we click on attach file or submit button, then it displays file upload pop-
up.
Selenium cannot handle this pop-up as it is a standalone type.
So to handle this we don’t click on attach file, instead we directly specify the path of the file
by using sendKeys().
Characteristics
We can drag the pop-up.
We cannot inspect the pop-up.
Sample HTML Source Code
<html>
<body> <form>
<input type = "file" name = "Upload File">
</form>
</body>
</html>
To copy the path of the file, Hold Shift -> Right Click -> Copy as Path
Synchronization
      The process of matching Selenium speed with the application speed without using
       Thread.sleep() is called Synchronization.
Limitations of Thread.sleep()
         1. For n number of pages, we specify n-1 number of times Thread.sleep().
         2. It waits until the specified time gets over, then only it will give the control to
             next line.
    In Selenium Synchronization can be handled in multiple ways.
         1. Implicit Wait
         2. Explicit Wait or Dynamic Wait
         3. Fluent Wait
         4. Wait For Pages
         5. Custom Wait
         6. Etc.,
Implicit Wait
      It is used to handle the Synchronization of only two methods, that is., findElement()
       and findElements().
      This statement will be written only once throughout the script.
      To specify the Implicit Wait, we write the below statement
       driver.manage().timeouts().implicitlyWait(duration,timeUnit);
      Implicit wait takes two parameters as an input, that is.,
            1. Duration
            2. Time Unit -> Example for Enum
      In Implicit Wait Time Unit can be in
            1. Days
            2. Hours
            3. MicroSeconds
          4.   MilliSeconds
          5.   Minutes
          6.   NanoSeconds
          7.   Seconds
Write a script to handle Synchronization by using Implicit Wait
     {
               System.setProperty("webdriver.gecko.driver","Softwares/geckodriver.exe/");
               WebDriver driver = new FirefoxDriver();
               driver.manage().window().maximize();
               driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
               driver.get("https://automation.lab/login.do");
               driver.findElement(By.name("username")).sendKeys("admin");
               driver.findElement(By.name("Password")).sendKeys("admin123");
               driver.findElement(By.id("login button")).click();
               driver.findElement(By.xpath("//div[text()='tasks']")).click();
               driver.findElement(By.xpath("//div[text()='reports']")).click();
      }
Flowchart of Implicit Wait
                    Element is present
                         or not
           Yes                                 No
 Return the address                      Implicit Wait is
   of the element                        specified or not
                                                                                    Wait for 0.5
                   Yes                              No                            seconds or 500
                                                                                    milliconds
 Implicit Wait time is                 NoSuchElementExists/
     over or not                         Empty Array List                        No
                            Yes
Explanation
  1. When the control comes to findElement()/findElements() it will verify whether
     element is present or not.
  2. If the element is present, it will return the address of the matching element.
  3. If the element is not present then it will verify whether Implicit Wait is specified or
     not.
  4. If Implicit Wait is not specified then it will throw NSEE/Empty Array.
  5. If Implicit Wait is specified then it will verify whether Implicit Wait time is over or
     not.
  6. If Implicit Wait is over then it will throw NSEE.
  7. If Implicit Wait time is not over then it will wait for 0.5 seconds.
  8. For every cycle it waits for 0.5 seconds is called as Polling period and the cycle
     continues until:
     a. Element is found.
     b. Implicit Wait time gets over.
Explicit Wait
*******************WRITE ABSENT NOTES***********************
TestNG
TestNG is a unit testing framework used by developers to perform WBT.
Why Testers?
      To run multiple scripts at one shot
      To generate report/result
      To achieve parallel execution
      To perform verification (assertion)
Steps to download TestNG for Eclipse
   Open Eclipse
   Click on Help
   Eclipse Marketplace
       Search for TestNG
       Install
       Accept the risk
       Finish
Steps to add TestNG to the project
   Right click on the project
   Build Path
   Add Libraries
   TestNG
   Next
   Finish
Note: J Unit is also a framework mainly used for WBT but using this we cannot achieve
parallel execution & no inbuild report generation is present.
Parameters of TestNG
How do you specify priority in TestNG
In TestNG to specify the priority, we use the parameter called “Priority”. By default, the value
of priority is zero. If the priority value is same, then it will execute based on the ASCII
(American Standard Code for Information Interchange).
Public class Demo1
{
@Test(priority = 1)
Public void test1()
{
        Reporter.log(“hello”,true);
}
@Test
Public void test2()
{
        Reporter.log(“world”,true);
}
}
How do you execute same test case multiple times using TestNG
By using the parameter called invocationCount. By default, the value of invocationCount is 1.
If we specify it as zero or lesser, then it will skip the test case.
Public class Demo1
{
@Test(invocationCount = 3, priority = 1)
Public void test1()
{
        Reporter.log(“hello”,true);
}
@Test
Public void test2()
{
        Reporter.log(“world”,true);
}
}
How do you skip the test case using TestNG
By using a parameter called “enabled” and assigning Boolean value as false.
Public class Demo1
{
@Test(enabled = false)
Public void test1()
{
        Reporter.log(“hello”,true);
}
@Test
Public void test2()
{
        Reporter.log(“world”,true);
}
}
How do you specify dependency between the annotations?
By using the parameter called dependsOnMethods
Public class Demo1
{
@Test
Public void compose()
{
        Reporter.log(“message composed”, true);
}
@Test(dependsOnMethods = “compose”)
Public void sentItems()
{
Reporter.log(“message sent”, true);
Assert.fail();
}
@Test(dependsOnMethods = “sentItems”)
Public void trash()
{
Reporter.log(“message deleted”, true);
}
Important Annotations of TestNG
    1. @BeforeSuite
    2. @BeforeTest
    3. @BeforeClass
    4. @BeforeMethod
    5. @Test
    6. @AfterMethod
    7. @AfterClass
    8. @AfterTest
    9. @AfterSuite
    10. @DataProvider
   11. @Parameter
   12. @FindBy
Note:
       In real time, for each and every test case we develop a separate class.
       In every test case we perform common actions such as opening and closing the
        application.
       In order to avoid the code repetition and also multiple object creations, we can make
        this as generic.
       TestNG provides annotations to achieve this. Such as:
            1. @BeforeMethod – All the prerequisites before performing the action should
                 be written here.,
            2. @Test – To perform the action as JVM recognizes it.
            3. @AfterMethod – All the post actions after executing the application should
                 be written here. Such as: Closing the application, Capturing the screenshot,
                 etc.
       In order to access the generic class methods, we use Inheritance (Extends).
Generic Script
Runner Script
Assertion in TestNG (Verification)
       In TestNG, to perform the verification we use Assert class.
       Verification is the process of validating whether the company’s development and the
        client’s requirement are syncing or not.
       Assert is an inbuilt class from TestNG framework.
       From Assert class we call a static method called assertEquals and parameterize it
        with two arguments such as Actual Result and Expected Result.
       Assert.assertEquals(ExpectedResult, ActualResult);
Case1: If actual and expected are same
   1.   Test case is pass.
   2.   It will continue with the execution.
   3.   It will not throw any exceptions.
   4.   Green colour tick mark is displayed.
Case2: If actual and expected are not same
   1. Test case is failed.
   2. It will stop the execution (It will stop executing the current test annotation and
      executes the remaining).
   3. It will throw an exception (Assertion Error)
   4. Blue colour cross mark is displayed.
Write a script to perform Verification using TestNG
{
        @Test
        public void runner()
        {
                System.setProperty("webdriver.gecko.driver", "./Softwares/geckodriver.exe");
                WebDriver driver = new FirefoxDriver();
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.get("https://www.facebook.com");
                String title = driver.getTitle();
                Assert.assertEquals(title, "Facebook - log in or sign up");
                System.out.println("India");
        }
}
How do you handle partially dynamic type?
Here, we use a method called assertTrue() to achieve it.
Assert.assertTrue(title.contains("Facebook"));
How do you wontedly fail a test case?
By using assert.fail
SoftAssert or Verify
       In real time even through the comparison gets failed and if we want to continue the
        execution, we use SoftAssert.
       Here we use a class called SoftAssert which is a concrete class and consists of non-
        static members.
       We also invoke a method class assertEquals and parameterize it will two arguments
        such as Actual Result and Expected Result.
       After the execution of SoftAssert, to consolidate we use assertAll() and it should
        always be the last statement.
Write a script to perform verification by using SoftAssert
Syntax:
SoftAssert sa = new SoftAssert()
sa.assertEquals(Actual Result , Expected Result)
sa.assertAll();
Script:
{
          @Test
          public void runner()
          {
                  System.setProperty("webdriver.gecko.driver", "./Softwares/geckodriver.exe");
                  WebDriver driver = new FirefoxDriver();
                  driver.manage().window().maximize();
                  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                  driver.get("https://www.facebook.com");
                  String title = driver.getTitle();
                  SoftAssert sa = new SoftAssert();
                  sa.assertEquals(title, "hello");
                  System.out.println("India");
                  sa.assertAll();
          }
}
POM (Page Object Model) Concept
driver.get("https://www.facebook.com");
WebElement ele = driver.findElement(By.id("email"));
ele.sendKeys("abcedef");
Thread.sleep(1500);
driver.navigate().refresh();
Thread.sleep(1500);
ele.sendKeys("admin"); //exception
       In the above example, as soon as the page gets refreshed, the element address will
        get changed and if we try to perform the action on the same element then it will
        throw StaleElementReferenceException. Stale refers to old or expired.
       To handle this exception, we go for POM (Page Object Model).
       findElement() – It fetches the address only for the first time and performs the action
        on same address.
       @FindBy – Each and every time it fetches the new or updated address and stores it.
Note: Annotations are faster compared to methods.
POM (Page Object Model)
POM is one of the frameworks and also a Java designed pattern, mainly used to handle
StaleElementReferenceException.
Advantages of POM
   1.   It is used to handle StaleElementReferenceException.
   2.   To achieve Encapsulation.
   3.   POM is also called Object Repository (It stores Element addresses).
   4.   POM is classified into 3 stages:
             a. Declaration
             b. Initialization
             c. Utilization
           Declaration: In POM we declare the elements by using @FindBy (annotation) and
           make it as private.
           Syntax: @FindBy(AN = “AV”)
                       Private WebElement ele;
           Initialization: In POM we initialize the elements by using constructor.
           Here, we use a class Page factory which is a concrete class and invoke a method
           called inItElements() which is a static method and parameterize it with two or
           more elements that is driver and this.
           Driver – It consists of address of the application.
           This – It points to current page or object.
               Public loginpage (WebDriver driver)
               {
                       PageFactoryElements(driver,this);
               }
           Utilization: In POM we utilize the elements by developing methods. For every
           element, we develop a separate a method which refers to Method Driven
           Framework. The major drawback of POM is, the time taken to design it is more.
           public void Enter usn()
           {
               Usn.sendKeys(“admin”)
           }
           Public void Enter pwd()
           {
           Pwd.sendKeys(“admin@223”);
           }
POM Script
public class POMScript1
{
       @FindBy(id="email")
       private WebElement uName;
       public POMScript1(WebDriver driver)
       {
               PageFactory.initElements(driver, this);
       }
       public void passData()
       {
               uName.sendKeys("admin");
       }
}
Runner Script
public class Demo1
{
       @Test
       public void validData() throws InterruptedException
      {
            System.setProperty("webdriver.gecko.driver","./Softwares/geckodriver.exe");
            WebDriver driver = new FirefoxDriver();
            driver.get("https://www.facebook.com");
            POMScript1 p = new POMScript1(driver);
            p.passData();
            Thread.sleep(1500);
            driver.navigate().refresh();
            Thread.sleep(1500);
            p.passData();
      }
}
******Write POM Script*************