Wednesday, June 26, 2024

Capturing Screenshots in Selenium WebDriver

 

Capturing Screenshots in Selenium WebDriver:

 

·  Capture Screenshot: The TakesScreenshot interface is used to capture the screenshot. The getScreenshotAs method captures the screenshot and stores it in a File object.

·  Save Screenshot: The screenshot is saved to a specified location using FileHandler.copy.

 

package AlertFrameWindowsBasics;

 

import java.io.File;

import java.io.IOException;

 

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class TakeScreenShotOfPage {

 

            public static void main(String[] args) throws IOException {

                        // class + interface ==  some predefined methods

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        // . Represents current project folder name

 

                        //                     //open chrome browser

                        WebDriver  driver =  new ChromeDriver();

//                     driver.get("https://www.google.com/");

                        driver.get("https://mvnrepository.com/artifact/commons-io/commons-io/2.16.0");

                        //**************************************

 

                        //                     TakesScreenshot(I)  - predefined Interface in Selenium

                        //   getScreenshotAs() - used to take screenshot of web page

                        // OutputType --  interface   

                        File srcFile =    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE) ;

 

                        System.out.println("src file="+srcFile);

                        // src file=C:\Users\Lenovo\AppData\Local\Temp\screenshot12776774740905017780.png

 

                        //         Fileutils -->    commons-io .jar file

                        // Download jar file from maven repository  and add to current project

                        // https://mvnrepository.com/

                        //

                        // add "commons -io .jar" file to project =  similar to adding selenium-java .jar file to project

 

                        // copy file into destFile

                        File destFile = new File("C:\\brahma\\Practise\\SelniumPractiseNew\\March52024MyWorkspace\\SeleniumMay52024\\src\\AlertFrameWindowsBasics\\screenshot1.png");

                        FileUtils.copyFile(srcFile, destFile);

 

                        System.out.println("ends ");

 

 

            }

 

}

           

 

 

*** FAQ / IQ  Write a code to take screen shot of the page ?

 

 

How to take screenshot manually ?

press 'prnt Sc ' button in keyboard  and Paste in word document-  -- full screens shot  with task manager and date and time

           (Or)

Alt + Prt Scr  --  and paste in word document  -->     no date and time


Handling Auto Suggestions

 

Handling Auto Suggestions

when we type something, it displays some suggestions/ options.

 

When working with auto-suggestions, the common tasks involve typing into an input field and then selecting one of the suggested options

 

  rama

  rama rao

  ramayya institute of technology

 

package AlertFrameWindowsBasics;

 

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class Autosuggestions {

 

            public static void main(String[] args) throws InterruptedException {

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        // . Represents current project folder name

 

                        //                     //open chrome browser

                        WebDriver  driver =  new ChromeDriver();

                        driver.get("https://www.google.com/");

                        //*******************************************

                        // Enter 'rama' in search box

                        driver.findElement(By.name("q")).sendKeys("rama");

 

                        Thread.sleep(5000);

 

                        // get all suggestions 

                        //div[@class='erkvQe']//ul[@role='listbox']/li  or (//ul[@role='listbox'])[1]/li

                        // or //div[@class='erkvQe']//ul[@role='listbox']/li/div//div[@class='lnnVSe']

                       

                        // //ul[@jsname='bw4e9b']/li

                        //ul[@jsname='bw4e9b']/li//div[@class='wM6W7d']/span

//                     (//ul[@jsname='bw4e9b']/li//div[@class='mus_il'])[1]

                       

                                    List<WebElement>     autoSuggestions = driver.findElements(By.xpath("//ul[@jsname='bw4e9b']/li//div[@class='wM6W7d']/span|(//ul[@jsname='bw4e9b']/li//div[@class='mus_il'])[1]"));

                                    int autoSuggestionsCnt = autoSuggestions.size();

                                    System.out.println("autoSuggestionsCnt="+autoSuggestionsCnt);

                                   

                        //1  for loop with index no

                                    for(int i=0;i<=autoSuggestionsCnt-1;i++)

                                    {

                                                String  suggestionNames= autoSuggestions.get(i).getText();

                                                System.out.println("suggestionNames="+suggestionNames);

                                    }

                        //                     suggestionNames=ramanna s lamani

                        //                     suggestionNames=ramalinga reddy

                        //                     suggestionNames=ramamurthy nagar

                        //                     suggestionNames=ramabanam

                        //                     suggestionNames=ramaiah institute of technology

                        //                     suggestionNames=ramachari serial

                        //                     suggestionNames=ramayan

                        //                     suggestionNames=ramanagara

                        //                     suggestionNames=ramaiya vastavaiya

                        //                     suggestionNames=ramadan 2024

 

 

                        // HW 2. for each loop

 

                        // Hw 3 iterator()

 

                        //  Hw 4 use listIterator()

 

 

            }

 

}

 

 

 

Capturing Screenshots in Selenium WebDriver:

 

·  Capture Screenshot: The TakesScreenshot interface is used to capture the screenshot. The getScreenshotAs method captures the screenshot and stores it in a File object.

·  Save Screenshot: The screenshot is saved to a specified location using FileHandler.copy.

 

package AlertFrameWindowsBasics;

 

import java.io.File;

import java.io.IOException;

 

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class TakeScreenShotOfPage {

 

            public static void main(String[] args) throws IOException {

                        // class + interface ==  some predefined methods

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        // . Represents current project folder name

 

                        //                     //open chrome browser

                        WebDriver  driver =  new ChromeDriver();

//                     driver.get("https://www.google.com/");

                        driver.get("https://mvnrepository.com/artifact/commons-io/commons-io/2.16.0");

                        //**************************************

 

                        //                     TakesScreenshot(I)  - predefined Interface in Selenium

                        //   getScreenshotAs() - used to take screenshot of web page

                        // OutputType --  interface   

                        File srcFile =    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE) ;

 

                        System.out.println("src file="+srcFile);

                        // src file=C:\Users\Lenovo\AppData\Local\Temp\screenshot12776774740905017780.png

 

                        //         Fileutils -->    commons-io .jar file

                        // Download jar file from maven repository  and add to current project

                        // https://mvnrepository.com/

                        //

                        // add "commons -io .jar" file to project =  similar to adding selenium-java .jar file to project

 

                        // copy file into destFile

                        File destFile = new File("C:\\brahma\\Practise\\SelniumPractiseNew\\March52024MyWorkspace\\SeleniumMay52024\\src\\AlertFrameWindowsBasics\\screenshot1.png");

                        FileUtils.copyFile(srcFile, destFile);

 

                        System.out.println("ends ");

 

 

            }

 

}

           

 

 

*** FAQ / IQ  Write a code to take screen shot of the page ?

 

 

How to take screenshot manually ?

press 'prnt Sc ' button in keyboard  and Paste in word document-  -- full screens shot  with task manager and date and time

           (Or)

Alt + Prt Scr  --  and paste in word document  -->     no date and time

Handling Multiple Browser Windows in Selenium

 

Handling Multiple Browser Windows in Selenium

In Selenium WebDriver, handling multiple browser windows involves switching between different windows or tabs that the browser might open during a test session. Here's how you can manage multiple browser windows:

1. Basic Concept

Every browser window or tab has a unique identifier known as a window handle. Selenium provides methods to get the current window handle, get all window handles, and switch between windows using these handles.

2. Key Methods

  • getWindowHandle(): Returns a string representing the current window handle.
  • getWindowHandles(): Returns a set of strings representing all window handles.
  • switchTo().window(String handle): Switches the focus to the specified window.

 

 

package AlertFrameWindowsBasics;

 

import java.util.Iterator;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class MultipleBrowserWindosHandling1 {

 

            public static void main(String[] args) throws InterruptedException {

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        // . Represents current project folder name

 

                        //                     //open chrome browser

                        WebDriver  driver =  new ChromeDriver();

 

                        // get("url ") - to open the url in chrome browser

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");

                        //*************************************

                        //click 'Open  Login form' button   - it opens new window - browser -2

                        driver.findElement(By.id("loginid")).click();

                        Thread.sleep(5000);

 

                        // get browsers count

                        Set<String> allBrowserWndAddresses = driver.getWindowHandles();

                       

                        //     can be used to get all the browser window addresses and store into Set object i.e allBrowserWndAddresses

                        int browsersCnt= allBrowserWndAddresses.size();

                        System.out.println("browsersCnt="+browsersCnt);// browsersCnt=2

 

                        // switch to new browser window  i.e window-2

//                     driver.switchTo().window("browser-2 addres");

 

                        // get browser-1 address

                        Iterator<String>  it =allBrowserWndAddresses.iterator();

                        String browser1Address = it.next();

 

                        System.out.println("browser1Address="+browser1Address);

 

                        // get browser-2 address

                        String browser2Address=  it.next();

 

                        System.out.println("browser2Address="+browser2Address);

                        // alert -->

                        // frame -->frame("");

 

                        // Switch to browser -2

                        // Window("browser window address")      

                        driver.switchTo().window(browser2Address);

 

                        //enter 'ramu' in un textbox userid

                        driver.findElement(By.id("userid")).sendKeys("Ramu");

 

                        //enter 'mercury' in password -pwdid

                        driver.findElement(By.id("pwdid")).sendKeys("mercury");

 

                        Thread.sleep(5000);

 

                        //  close browser -2 window

                        // close the browser which is currently focussed

                        //                     // it will close currently focussed browser window i.e browser-2

                        driver.close();            

                        // browser -1 or browser2  ???  close browser-2

 

                        //   switch to Main page i.e Browser -1

                        driver.switchTo().window(browser1Address);

 

                        // enter 'Rao' in last name -lastname

                        driver.findElement(By.name("lastname")).sendKeys("Rao");

 

                        Thread.sleep(5000);

 

                        //  switch to invalid browser address by passing invalid address

//                                             driver.switchTo().window("Abcddfsfa");

 

                        //  org.openqa.selenium.NoSuchWindowException: no such window

                        //   there is no ele present    --> NoSuchElementException

                        //               no alert     -->  NoAlertPresentException

                        //      Frame is not there --> NoSuchFrameException

                        //  Window -->                        NoSuchWindowException

 

 

 

            }

 

}

 

 

 -                                 

// HW open AllWeboebjects.html page, click 'Webtable'all  button and it opens new window  and

    Switch to new window and get table count, close browser2  i.e Webtableall.html page.

 Go to Browser-1  and enter some value in "password" text box

                                   

---------------------------------------                        

***  FAQ  how can you handle multiple browser windows ?

 

 

Q: Open 3 browser windows and get all browser Titles ?

 

package AlertFrameWindowsBasics;

 

import java.util.Iterator;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class GetAllBrowserTitles {

 

            public static void main(String[] args) throws InterruptedException {

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        // . Represents current project folder name

 

                        //                     //open chrome browser

                        WebDriver  driver =  new ChromeDriver();

 

                        // get("url ") - to open the url in chrome browser

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");

 

                        //click 'Open  Login form' button   - it opens new window - browser -2

                        driver.findElement(By.id("loginid")).click();

 

                        Thread.sleep(4000);

 

                        // click 'webtable all'  button  - it opens new window - browser -3 -allid

                        driver.findElement(By.id("allid")).click();

                        Thread.sleep(4000);

 

                        // click 'Simple allObjects'  button simpleid - it opens new window - browser -4 -simpleid

                        driver.findElement(By.id("simpleid")).click();

                        Thread.sleep(4000);

 

                        // get all browsers Count

                        Set<String> allWindowAddresses = driver.getWindowHandles();

                       

                        System.out.println("browsersCnt=" +allWindowAddresses.size());

                        //All browser count  =4

 

                        // get all browser windows addresses using iterator() using while loop

                        Iterator<String>  it = allWindowAddresses.iterator();

 

                        //     br1 br2 - 3    4 

                        while(it.hasNext())

                        {

                                    String address =  it.next();

                                    driver.switchTo().window(address);

                                    String title =  driver.getTitle();

                                    System.out.println("title="+title);

                        }

                       

           

                                    //  switch to each browser

 

                                    // get title                  

 

 

                        //                                             title=All webobjects MyTitle Sumanth

                        //                                             title=Simple all objects Title

                        //                                             title=WebtableAll Title

                        //                                             title=Login page

 

                        //HW   get all browser titles using for each loop

                        System.out.println("get all browser titles using for each loop************************");

                       

 

                        //                     title=All webobjects MyTitle Sumanth

                        //                                             title=Simple all objects Title

                        //                                             title=WebtableAll Title

                        //                                             title=Login page

 

 

 

 

            }

 

}

 

 

HW :WAP  to develop  a resuable method to  close browser based on given title

   closeBrowserBasedOngivenTitle("Login page");

   closeBrowserBasedOngivenTitle("WebtableAll Title");

 

Code:

 

HW WAP to develop a seperate a method to Close all browser windows except 'Login page' title  -2nd way for each loop ?

public static void closeAllBrowsersExceptGivenTitle(String expTitle)

{

 

 

}

 

 

 

Open 3 browser windows , Develop  resusable method to switch to Window Based on title name ?

 

switchToBrowserBasedOnGivenTitle(String title)

{

 

 

}

           

switchToBrowserBasedOnGivenTitle("Login page");

switchToBrowserBasedOnGivenTitle("WebtableAll Title");

 

           

package AlertFrameWindowsBasics;

 

import java.util.Iterator;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class SwitchToBrowserBasedOnTitlle {

           

           

            int a;//  def val for instance var -0

            float f; // 0.0

            String s;//  null

            static WebDriver driver;// null

           

            //Develop  switchToBrowserBasedOnGivenTitle("Login page")

            public static void switchToBrowserBasedOnGivenTitle(String title)

            {

                        System.out.println("driver="+ driver);// nul;;

                        Set<String> allBrowserWndAddresses = driver.getWindowHandles();

                        //                                   null.   --> NullpointerException

                        boolean TitleFound = false;

                       

                        Iterator<String>  it = allBrowserWndAddresses.iterator();

                        while(it.hasNext())

                        {                                  

                                    String address =it.next();

                                    driver.switchTo().window(address);

                                    String actualTitle = driver.getTitle();

                                   

                                    if(title.equals(actualTitle))

                                    {

                                     System.out.println("title is found ="+ title);

                                     TitleFound = true;

                                     break;

                                    }                                  

                        }

                       

                        if(TitleFound == true)

                        {

                                    System.out.println("title is found ="+ title);

                        }

                        else

                        {

                                    System.out.println("title =" +title +" is not found. Plz give valid/ correct title");

                        }

                       

            }

 

            public static void main(String[] args) throws InterruptedException {

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        // . Represents current project folder name

 

                        //                     //open chrome browser

//                                             WebDriver  driver =  new ChromeDriver();

                        driver =  new ChromeDriver();

 

                        // get("url ") - to open the url in chrome browser

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");

 

                        //click 'Open  Login form' button   - it opens new window - browser -2

                        driver.findElement(By.id("loginid")).click();

 

                        Thread.sleep(4000);

 

                        // click 'webtable all'  button  - it opens new window - browser -3

                        driver.findElement(By.id("allid")).click();

                        Thread.sleep(4000);

 

                        // click 'Simple allObjects'  button simpleid - it opens new window - browser -4

                        driver.findElement(By.id("simpleid")).click();

                        Thread.sleep(4000);

 

                        // Call switchtoWindow() by passing -Login page

                        switchToBrowserBasedOnGivenTitle(" Login page ");

 

                                    // Enter user . pwd

                                    driver.findElement(By.id("userid")).sendKeys("Ramu");

                                    driver.findElement(By.id("pwdid")).sendKeys("mercury");

 

                        // close browser

                        driver.close();

 

                        //HW  Switch to Window with title- All webobjects MyTitle Sumanth

                        // HW Enter first name, last name

                        //         HW      close browser

 

 

                        //HW  Go  to browser with title =  Simple all objects Title

                        // HW Select 'Honda in bikes dropdown

 

                        // If given title-  is not found for  browser?

                        switchToBrowserBasedOnGivenTitle("My Login title");

 

            }

 

}

 

 

FAQ Difference  between GetWindowHandle() and GetWindowHandles()?

Feature

getWindowHandle()

getWindowHandles()

 

Purpose

Retrieve the handle of the current window

Retrieve the handles of all open windows

 

Return Type

String

Set<String>

 

Number of Handles Returned

Single handle

Multiple handles

 

Common Usage

Store or switch back to the current window

Iterate through and switch between multiple windows

 

Example Use Case

Handling a single window

Handling multiple windows, such as when a new tab is opened

 

 

String GetWindowHandle()  can be used to get currently focussed browser window address

                         return type String

 

GetWindowHandles()  -can be used to get all browser window addresses

                        return type set<String>

 

HW Develop resuable method to  closeAllBrowserWindows();

 

closeAllBrowserWindows()

{

  //  code

// code

}

 

Call:  closeAllBrowserWindows();

 

-------------------------------------------

HW WAP to  open 2 browser windows ,  

Switch to browser 2 by passing browser number i.e 2

 

SwicthToBrowser(int browserNo)

{

 

}

 

SwicthToBrowser(2);

SwicthToBrowser(1);

 

FAQ where did u use Method overloading (polymorphism) in ur project ?

 

SwitchToBrowser(int browserno)

{

 

}

 

SwitchToBrowser(String title)

{

 

 

}

 

 

HW WAP to  open 2 browser windows ,  

close browser 2 by passing browser number i.e 2

 

CloseBrowser(int browserNo)

{

 

}

 

CloseBrowser(2);

CloseBrowser(1);

 

FAQ how can you handle multiple tabs/ browser windows?

  Same code ..

 

HW WAP to  get all browser titles and addresss , store into  hashmap<String,String>  and return hashmap, display title and address?

 

//HW  Handle -ve scenario- if given browser title is not there, display proper msg "Given browser is not found with given title="   while closing browser based on given title ="

 

ex: closeBrowserByTitle("Login page Form 123");

// if title  =Login page Form 123 is not available , display proper msg ?

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...