[Selenium+Java] How to Take Screenshot in Selenium WebDriver

Posted alicegu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Selenium+Java] How to Take Screenshot in Selenium WebDriver相关的知识,希望对你有一定的参考价值。

Original URL: https://www.guru99.com/take-screenshot-selenium-webdriver.html

Screenshots are desirable for bug analysis. Selenium can automatically take screenshots during execution. You need to type cast WebDriver instance to TakesScreenshot.

技术分享图片

Taking Screenshot in Selenium is a 3 Step process

Step 1) Convert web driver object to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

Step 2) Call getScreenshotAs method to create image file

File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

Step 3) Copy file to Desired Location

Example: In this example we will take screenshot of http://demo.guru99.com/V4/ & save it as C:/Test.png

package Guru99TakeScreenshot;

import java.io.File;

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.firefox.FirefoxDriver;

import org.testng.annotations.Test;

public class Guru99TakeScreenshot {

    @Test

    public void testGuru99TakeScreenShot() throws Exception{

		WebDriver driver ;
    	System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
    	driver = new FirefoxDriver();

        //goto url

        driver.get("http://demo.guru99.com/V4/");

        //Call take screenshot function

        this.takeSnapShot(driver, "c://test.png") ;     

    }

    /**

     * This function will take screenshot

     * @param webdriver

     * @param fileWithPath

     * @throws Exception

     */

    public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{

        //Convert web driver object to TakeScreenshot

        TakesScreenshot scrShot =((TakesScreenshot)webdriver);

        //Call getScreenshotAs method to create image file

                File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

            //Move image file to new destination

                File DestFile=new File(fileWithPath);

                //Copy file at destination

                FileUtils.copyFile(SrcFile, DestFile);

    }

}

以上是关于[Selenium+Java] How to Take Screenshot in Selenium WebDriver的主要内容,如果未能解决你的问题,请参考以下文章

[Selenium+Java] How to Take Screenshot in Selenium WebDriver

[Selenium+Java] How to use IntelliJ IDEA & Selenium Webdriver

[Selenium+Java] How to Upload & Download a File using Selenium Webdriver

How to set Selenium Python WebDriver default timeout?

How to click on a point on an HTML5 canvas in Python selenium webdriver

how to write an email