Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Click on a Hyperlink Using Java Selenium WebDriver?
Next article icon

How to Take a Screenshot in Selenium WebDriver Using Java?

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Selenium WebDriver is a collection of open-source APIs used to automate a web application’s testing. To capture a screenshot in Selenium, one must utilize the Takes Screenshot method. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used to automate web application testing to verify that it works as expected. It supports many browsers. Here we will be taking the example of Chrome.

Table of Content

  • Why take screenshots in Selenium?
  • How to take screenshots in Selenium WebDriver?
  • Example of Taking a Screenshot in Selenium WebDriver
  • Conclusion
  • Frequently Asked Questions on How to Take a Screenshot in Selenium WebDriver Using Java

Why take screenshots in Selenium?

The document talks about the importance of screenshots in automated testing with Selenium. Here is the key idea in simpler terms:

  • Re-running an entire test after a failure wastes time. Ideally, the test should pinpoint the exact error.
  • Similarly, testers need to verify if an application works as expected visually. Screenshots help with that.
  • Selenium WebDriver, a popular test automation tool, lets you take screenshots during tests.

Here are some situations when screenshots are handy in Selenium tests:

  • When the application crashes or behaves strangely.
  • When a test fails an assertion (a built-in check to verify something is true).
  • When the test has trouble finding elements on a webpage.
  • When the test times out waiting for elements to load.

How to take screenshots in Selenium WebDriver?

Syntax:

File file = ((TakesScreenshot) driver) ;

Here, we will learn how to take a screenshot in the Selenium web driver and highlight the element using Java Binding.

Screenshots are required for bug analysis, especially in the case of test case failure. Whenever a test case fails, we need some attachment to verify that failure. Selenium can automatically take a screenshot during execution, and we can also mark a border to highlight that element.

Example of Taking a Screenshot in Selenium WebDriver

Now lets see how can you take screenshot in Selenium WebDriver:

Step 1. Take a screenshot and store it in a file format

Step 2. Copy screenshot to a location using CopyFile method  

FileUtils.copyFile(File, new File(“location where you want to save the image” +FileName+ “.jpeg”)); 

Step 3. Create a border around the element: Using the JavaScript executor, we can create a border around the desired element.

JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“arguments[0].style.border = ‘3px solid red'”, Element);

Refer to the complete code below for the implementation part

Java
// Java program how to take // a screenshot in Selenium // WebDriver  import java.io.*;  class GFG {     public static void main(String[] args)     {         // Setting webDriver to chrome         System.setProperty("webdriver.chrome.driver",                            "driver path");         driver = new ChromeDriver();         driver.get("https://www.google.co.in");          WebElement Element = driver.findElement(             By.xpath("//input[@name='q']"));          // Assignments to webDriver         MakeBorder(Element);         Thread.sleep(2000);         TakeScreenshot("GooglePage");         driver.quit();     }      // Function to Take screenshot     public static void TakeScreenshot(String FileName)         throws IOException     {         // Creating instance of File         File File = ((TakesScreenshot)driver)                         .getScreenshotAs(OutputType.FILE);          FileUtils.copyFile(File,                            new File("image location"                                     + FileName + ".jpeg"));     }      // Function to Make border     public static void MakeBorder(WebElement Element)     {          JavascriptExecutor js = (JavascriptExecutor)driver;         js.executeScript(             "arguments[0].style.border = '3px solid red'",             Element);     } } 

Output

output of How to Take a Screenshot in Selenium WebDriver Using Java

output of How to Take a Screenshot in Selenium WebDriver Using Java

Conclusion

In conclusion, Selenium WebDriver allows you to take screenshots during automated tests to help point out the errors and verify application behavior. Screenshots are especially useful when tests fail or encounter unexpected issues.



Next Article
How to Click on a Hyperlink Using Java Selenium WebDriver?

R

rajatshandilya25
Improve
Article Tags :
  • Java
  • Selenium
  • Software Testing
  • selenium
Practice Tags :
  • Java

Similar Reads

  • How to refresh a webpage using java Selenium Webdriver?
    Refreshing a webpage is often necessary when you want to ensure that your tests or interactions are working with the latest content or to reset the state of a web page during automation. Selenium WebDriver makes this task straightforward with various methods available in Java. This article will demo
    3 min read
  • How to Click on a Hyperlink Using Java Selenium WebDriver?
    An open-source tool that is used to automate the browser is known as Selenium. Automation reduces human effort and makes the work comparatively easier. There are numerous circumstances in which the user wants to open a new page or perform a certain action with the click of the hyperlink. In this art
    4 min read
  • How to capture Screen Shot in Selenium WebDriver?
    Selenium is an open-source framework used mainly in web automation tasks. Its sole purpose is in testing web applications but it's not the only thing we can do with selenium. Selenium can also be used in other web-related tasks (such as web scraping, web element interaction, etc). Since Selenium is
    4 min read
  • Key press in (Ctrl+A) Selenium WebDriver using java
    Selenium WebDriver is a powerful tool for automating web applications, and it offers various ways to simulate user actions such as clicking, typing, and even pressing keyboard shortcuts. One of the common actions is selecting all text or elements on a page using the "Ctrl+A" key press. This is usefu
    3 min read
  • How to do session handling in Selenium Webdriver using Java?
    In Selenium WebDriver, managing browser sessions is crucial for ensuring that each test runs independently and without interference. A browser session in Selenium is identified by a unique session ID, which helps track and manage the session throughout the test. Proper session handling in Selenium W
    4 min read
  • How to ask the Selenium-WebDriver to wait for few seconds in Java?
    An open-source framework that is used for automating or testing web applications is known as Selenium. There are some circumstances when the particular component takes some time to load or we want a particular webpage to be opened for much more duration, in that case, we ask the Selenium web driver
    9 min read
  • How do I set the Selenium webdriver get timeout using Java?
    Setting timeouts is important for good automated testing in Selenium WebDriver. One important timeout is page load timeout. This controls how long Selenium waits to load a page when visiting a given URL. If there is no timeout, tests may be stuck when pages load slowly. This results in failed tests.
    2 min read
  • How to set Proxy in Firefox using Selenium WebDriver?
    In today’s fast-paced digital world, ensuring that web applications are tested under various network conditions is crucial. Setting up a proxy in Firefox using Selenium WebDriver allows testers to capture traffic, simulate different network environments, and comply with strict corporate policies, ma
    4 min read
  • How to run Selenium Running Test on Chrome using WebDriver
    Selenium is a popular open-source tool for automating web browser interactions. It works with different web browsers like Chrome, Firefox, and more, and different programming languages like Python or Java to write tests. What is a Selenium ChromeDriver?ChromeDriver is a separate executable that Sele
    3 min read
  • How to mute all sounds in chrome webdriver with selenium using Java?
    In some automated testing situations, the website may play audio or video. This may interfere with the test operation. To solve this problem, turning off all sounds in Chrome during Selenium WebDriver testing ensures a quieter environment. It improves the efficiency and accuracy of test results. Thi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences