• Selenium Video Tutorials

Selenium Webdriver - Capture Screenshots



Selenium Webdriver can be used to capture screenshots of a web page while running the automated steps. The screenshots are captured with the help of the TakeScreenshot method.

This method gives the instruction to the Selenium Webdriver to capture the screenshot. To capture the screenshot in a desired location, we would need to use the getScreenshotAs() method.

Let us now discuss the identification of an input box on a webpage shown in the below image. First, we would need to right click on the webpage, and then click on the Inspect button in the Chrome browser. Then, the corresponding HTML code for the whole page would be visible. For investigating a single element on a page, we would need to click on the left upward arrow, available to the top of the visible HTML code as highlighted below.

Selenium Capture Screenshots 1

Once we had clicked and pointed the arrow to the input box (highlighted in the below image), its HTML code was visible, both reflecting the input tagname(enclosed in <>).

<input name="name" id="name" type="text" class="form-control" placeholder="First Name">
Selenium Capture Screenshots 2

Let us take an example of the above page, where we would first enter some text in the input box with the help of the sendKeys() method and then take the screenshot of the entire web page.

Syntax

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("location where screenshot stored"));

Example

Code Implementation on ScreenshotCapture.java class file.

package org.example;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenshotCapture {
   public static void main(String[] args) throws InterruptedException, IOException {
      
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
      
      // Opening the webpage where we will identify an element
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");
      
      // Identify the input box with xpath locator
      WebElement e = driver.findElement(By.xpath("//*[@id='name']"));
      
      // enter text in input box
      e.sendKeys("Selenium");
      
      // Get the value entered
      String text = e.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // take full screenshot and store in project location
      File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(scrFile, new File("./ImageFullPage.png"));
            
      // Closing browser
      driver.quit();
   }
}

Dependencies added in pom.xml file −

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
      <dependency>
         <groupId>commons-io</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.12.0</version>
      </dependency>
   </dependencies>
</project>

Output

Entered text is: Selenium

Process finished with exit code 0

In the above example, we had first entered the text Selenium in the input box, and also retrieved the value entered in the console with the message - Entered text is: Selenium.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

Also, the screenshot with the filename ImageFullPage.png got captured in the project directory. On clicking it, we would get the captured screenshot of the entire web page.

Selenium Capture Screenshots 3

Let us take the same example as discussed above, where we would first enter some text in the input box with the help of the sendKeys() method and then take the screenshot of that element only. This can be done using the getScreenShotAs() method.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.xpath("value of xpath")).sendKeys("value entered"); 

// take screenshot of input box and store in project location
File scrFile = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("location where screenshot stored"));

Example

Code Implementation on ScreenshotCaptureElement.java class file.

package org.example;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenshotCaptureElement {
   public static void main(String[] args) throws InterruptedException, IOException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will identify an element
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // Identify the input box with xpath locator
      WebElement e = driver.findElement(By.xpath("//*[@id='name']"));

      // enter text in input box
      e.sendKeys("Selenium");

      // Get the value entered
      String text = e.getAttribute("value");
      System.out.println("Entered text is: " + text);

      // take screenshot of input box and store in project location
      File scrFile = e.getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(scrFile, new File("./ImageElement.png"));

      // Closing browser
      driver.quit();
   }
}

Dependencies added in pom.xml file −

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
      <dependency>
         <groupId>commons-io</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.12.0</version>
      </dependency>
   </dependencies>
</project>

Output

Entered text is: Selenium

Process finished with exit code 0

In the above example, we had first entered the text Selenium in the input box, and also retrieved the value entered in the console with the message- Entered text is: Selenium.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

Also, the screenshot with the filename ImageElement.png got captured in the project directory. On clicking it, we would get the captured screenshot of only the input box where we entered the text Selenium.

Selenium Capture Screenshots 4

Let us take the same example as discussed above, where we would try to enter some text in the input box with the help of the sendKeys() method and then take the screenshot of that step only if there is a failure in that step. This can be done using the getScreenShotAs() method added to the catch block (usually used for exception handling).

Syntax

Webdriver driver = new ChromeDriver();
try {

   // Identify the input box with incorrect xpath locator
   WebElement element = driver.findElement(By.xpath("<incorrect value of xpath>"));
   
   // enter text in input box
   element.sendKeys("Selenium");
   System.out.println("Step successfully executed");
}

catch(Exception e) {

   // take screenshot on failure and store in project location
   File scrFile = ((TakesScreenshot) driver). getScreenshotAs(OutputType.FILE);
   FileUtils.copyFile(scrFile, new File(".location where screenshot stored"));
   System.out.println("Element could not be found - Step failed");
}

Example

Code Implementation on ScreenshotCaptureException.java class file.

package org.example;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenshotCaptureException {
   public static void main(String[] args) throws InterruptedException, IOException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will identify an element
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      try {
	  
         // Identify the input box with xpath locator
         WebElement e = driver.findElement(By.xpath("//*[@id='names']"));

         // enter text in input box
         e.sendKeys("Selenium");
         System.out.println("Step successfully executed");
      }

      catch(Exception e) {
	  
         // take screenshot on failure and store in project location
         File scrFile = ((TakesScreenshot) driver). getScreenshotAs(OutputType.FILE);
         FileUtils.copyFile(scrFile, new File("./ImageException.png"));
         System.out.println("Element could not be found - Step failed");
      }

      // Closing browser
      driver.quit();
   }
}

Dependencies added in pom.xml file −

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
      <dependency>
         <groupId>commons-io</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.12.0</version>
      </dependency>
   </dependencies>
</project>

Output

Element could not be found - Step failed

Process finished with exit code 0

In the above example, our test launched a web page and tried to interact with an element. After the element could not be identified, the flow of execution moved to the catch block where we got the message in the console - Element could not be found - Step failed.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

Also, the screenshot with the file name ImageException.png got captured in the project directory. On clicking it, we would get the captured screenshot of the failed test step (which means, Selenium did not get entered in the input box).

Selenium Capture Screenshots 5

Thus, in this tutorial, we had discussed how to capture screenshots using the Selenium Webdriver.

Advertisements