How to Take a Screenshot Selenium Java
Selenium is an
open-source
web-based automation tool that is
implemented using a web driver. We will be using geckodriver
because Selenium 3 enables
geckodriver as the default WebDriver implementation for Firefox.
Pre-requisites:
- geckodriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
it takes 4 simple to take a screenshot:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver and browse to the website.
-
Convert webdriver object to
TakeScreenshot
. - Use the built-in function to get screenshot and save as file.
Let’s see all the above steps in the code. We will use
getScreenshotAs(OutputType>X< Target)
function to take screenshot.
import org.apache.commons.compress.utils.FileNameUtils; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; import java.util.List; public class TakeScreenshot { public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\Screenshot\\src\\main\\resources\\geckodriver.exe"; public static void main(String[] args) { //set firefox webdriver System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH); WebDriver driver = new FirefoxDriver(); //get the firefox browser & Browse the Website String siteLink = "https://www.oracle.com/java/"; driver.get(siteLink); //Convert webdriver object to TakeScreenshot TakesScreenshot scrShot = ((TakesScreenshot) driver); //Create image file File source = scrShot.getScreenshotAs(OutputType.FILE); //Set new destination & File Name String fileWithPath = "C:\\Users\\Momin-PC\\Desktop\\oracle.png"; File destination = new File(fileWithPath); //Copy file at destination try { FileUtils.copyFile(source, destination); } catch (Exception e) { e.printStackTrace(); } } }
Output:
All resources used in this tutorial are attached:
- source code
- geckdriver.exe
Comments
Post a Comment