James Hollingworth
James Hollingworth

Reputation: 14210

How to take a screenshot with Selenium WebDriver?

Is it possible to take a screenshot using Selenium WebDriver?

(Note: Not Selenium Remote Control)

Upvotes: 551

Views: 696322

Answers (30)

flamey
flamey

Reputation: 2379

Perl

my $driver = Selenium::Remote::Driver->new;
$driver->get('http://www.google.com');
$driver->capture_screenshot('viewpoint.png');
# or, if using Firefox, you can take full page screenshots
$driver->capture_screenshot('fullpage-ff-only.png', {'full' => 1});

Upvotes: 0

<Django(Python)>

You can take the screenshots of Django Admin on headless Google Chrome, Microsoft Edge and Firefox together.

First, pytest-django and selenium as shown below:

pip install pytest-django && pip install selenium

Then, create pytest.ini and conftest.py, test_1.py and __init__.py(Empty file) in tests folder as shown below. *pytest.ini should be put in the root directory of django-project folder and my answer explains that multiple conftest.py can be used:

django-project
 |-core
 |  └-settings.py
 |-my_app1
 |-my_app2
 |-pytest.ini
 └-tests
    |-__init__.py
    |-conftest.py 
    └-test_1.py

Then, set the code below to pytest.ini. *You need to set Screenshot to python_classes and screenshot_admin to python_functions otherwise they are not run according to my answer and I recommend to set tests to testpaths because it makes the test faster according to the doc:

# "pytest.ini"

[pytest]
DJANGO_SETTINGS_MODULE = core.settings
testpaths = tests
python_classes = Screenshot
python_functions = screenshot_admin

Finally, set the code below to tests/test_1. *My answer explains how to set window size of browsers in Selenium:

# "tests/test_1"

import os
import pytest
from selenium import webdriver

def take_screenshot(driver, name):
    os.makedirs(os.path.join("screenshot", os.path.dirname(name)), exist_ok=True)
    driver.save_screenshot(os.path.join("screenshot", name))

@pytest.fixture(params=["chrome", "edge", "firefox"], scope="class")
def driver_init(request):
    if request.param == "chrome":
        options = webdriver.ChromeOptions()
        options.add_argument("--headless=new")
        web_driver = webdriver.Chrome(options=options)
    if request.param == "edge":
        options = webdriver.EdgeOptions()
        options.add_argument("--headless=new")
        web_driver = webdriver.Edge(options=options)
    if request.param == "firefox":
        options = webdriver.FirefoxOptions()
        options.add_argument("--headless") 
        web_driver = webdriver.Firefox(options=options)
    request.cls.browser = request.param
    request.cls.driver = web_driver
    yield
    web_driver.close()

@pytest.mark.usefixtures("driver_init")
class Screenshot:
    def screenshot_admin(self, live_server):
        self.driver.set_window_size(1024, 768)
        self.driver.get(("%s%s" % (live_server.url, "/admin/")))
        take_screenshot(self.driver, "admin/" + self.browser + ".png")
        assert "Log in | Django site admin" in self.driver.title

Upvotes: 0

Nomad77
Nomad77

Reputation: 115

C# Selenium 4.9

driver.TakeScreenshot().SaveAsFile(path + filename + ".jpg");

Upvotes: 0

Lakshitha Samod
Lakshitha Samod

Reputation: 381

You can use the ashot library to take screenshots in Selenium WebDriver. Here's an example:

First, you need to add the ashot dependency to your project:

<dependency>
    <groupId>ru.yandex.qatools.ashot</groupId>
    <artifactId>ashot</artifactId>
</dependency>

Then, you can take a screenshot using the following code:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

public class ScreenshotExample {
    public static void main(String[] args) throws IOException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        Screenshot screenshot = new AShot().takeScreenshot(driver);
        ImageIO.write(screenshot.getImage(), "PNG", new File("screenshot.png"));
        driver.quit();
    }
}

This will take a screenshot of the current page and save it to a file named "screenshot.png".

Upvotes: 1

MT1
MT1

Reputation: 974

Excel VBA

Option Explicit

Private Sub Login()
    Dim driver As ChromeDriver
    Set driver = New ChromeDriver
    Dim sURL As String
    sURL = "https://www.bing.com/"
    Dim sFilename As String
    sFilename = "C:\Users\username\Downloads\screenshot-" & sURL & "-" & Format(Now(), "yyyymmddHHMMSS") & ".png"
    sFilename = Replace(sFilename, "://", "")
    sFilename = Replace(sFilename, "/", "")
    Call driver.Start("edge", sURL)
    driver.get (sURL)
    driver.Window.Maximize
    sbDelay (100000)
    driver.TakeScreenshot.SaveAs (sFilename)
    sbDelay (100000)
    driver.Quit
End Sub

Sub sbDelay(delay As Long): Dim i As Long: For i = 1 To delay:  DoEvents: Next i: End Sub 'old skool delay

I used the VBA type library that Microsoft support

https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

I used MS Edge - the Selenium version must match the version of Edge that you have installed.

Edge Version 110.0.1587.57

You will need to browse to the type library for your machine either 32 or 64 bit.

Tools > References > Selenium Type Library (Selenium64.tlb)

Upvotes: 0

pr96
pr96

Reputation: 1211

Updated 2022

To take a screenshot in Selenium, we use an interface called TakesScreenshot, which enables the Selenium WebDriver to capture a screenshot and store it in different ways. It has a got a method getScreenshotAs() which captures the screenshot and stores it in the specified location.

//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

In the above code, its convert the WebDriver object (driver) to TakeScreenshot. And call getScreenshotAs() method to create an image file by providing the parameter *OutputType.FILE.

We can use the File object to copy the image at our desired location, as shown below, using the FileUtils Class.

FileUtils.copyFile(screenshotFile , new File("C:\\temp\\screenshot.png));

Capture the full page

Selenium WebDriver doesn't provide the inherent capability to capture screenshots of the whole page. To capture the full-page screenshot, we have to use a third-party library named Ashot. It provides the ability to take a screenshot of a particular WebElement as well as a full-page screenshot.

Capture the screen size image

Screenshot screenshot = new Ashot().takeScreenshot(driver);

Capture the full page screenshot

Screenshot s=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(s.getImage(),"PNG",new File("<< file path>>"));

In the above code, 1000 is scrolled out time in milliseconds. In other words, it means that the program will scroll for each 1000 msec to take a screenshot.

Capture a elememnt

There are two ways to capture the screenshot of a web element in Selenium.

  • Take the fullscreen image and then crop the image as per the dimensions of the web element.
  • Using the getScreenshotAs() method on the web element. ( This is available only in selenium version 4.X)

Upvotes: 2

Jackin Shah
Jackin Shah

Reputation: 41

Yes, it is possible to take a snapshot of a web page using Selenium WebDriver.

The getScreenshotAs() method provided by the WebDriver API does the work for us.

Syntax: getScreenshotAs(OutputType<X> target)

Return type: X

Parameters: target – Check the options provided by OutputType

Applicability: Not specific to any DOM element

Example:

    TakesScreenshot screenshot = (TakesScreenshot) driver;
    File file = screenshot.getScreenshotAs(OutputType.FILE);

Refer to the below working code snippet for more details.

    public class TakeScreenShotDemo {

        public static void main(String[] args) {
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.get(“http: //www.google.com”);

            TakesScreenshot screenshot = (TakesScreenshot) driver;

            File file = screenshot.getScreenshotAs(OutputType.FILE);

            // Creating a destination file
            File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
            try {
                FileUtils.copyFile(file, destination);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

Visit Snapshot using WebDriver for getting more details.

Upvotes: 1

Aman Sharma
Aman Sharma

Reputation: 311

I use the following code in C# to take the full page or only a browser screenshot

    public void screenShot(string tcName)
    {
        try
        {
            string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
            string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
            ITakesScreenshot screen = driverScript.driver as ITakesScreenshot;
            Screenshot screenshot = screen.GetScreenshot();
            screenshot.SaveAsFile(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
            if (driverScript.last == 1)
                this.writeResult("Sheet1", "Fail see Exception", "Status", driverScript.resultRowID);
        }
        catch (Exception ex)
        {
            driverScript.writeLog.writeLogToFile(ex.ToString(), "inside screenShot");
        }
    }

    public void fullPageScreenShot(string tcName)
    {
        try
        {
            string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
            string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
            Rectangle bounds = Screen.GetBounds(Point.Empty);
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                }
                bitmap.Save(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
            }
            if (driverScript.last == 1)
                this.writeResult("Sheet1", "Pass", "Status", driverScript.resultRowID);
        }
        catch (Exception ex)
        {
            driverScript.writeLog.writeLogToFile(ex.ToString(), "inside fullPageScreenShot");
        }
    }

Upvotes: 0

Md. Imran Hassan
Md. Imran Hassan

Reputation: 11

Java

For newer version of Java, the FileUtils function doesn't work. Here the following function worked perfectly for screenshot copying.

import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.io.FileHandler;

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File destfile = new File(destination folder /filename.extension);
FileHandler.copy(scrfile, destfile);

Upvotes: 0

Rutu Shah
Rutu Shah

Reputation: 11

JAVA

Hi, you can take screenshot in selenium and here is the code given below with the help of which you can create screenshot in any selenium project and we can also generate screenshots for the failed scenario's in aws too.

    public boolean takeScreenshot(final String name) {
    String screenshotDirectory = System.getenv("WORKING_DIRECTORY");
    File screenshot = 
    ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    return screenshot.renameTo(new File(screenshotDirectory, 
    String.format("%s.png", name)));
    }

Upvotes: 0

a Learner
a Learner

Reputation: 5042

You can take screenshot of webpage visible portion in browser as:

First import:

import java.io.File;
import com.google.common.io.Files;

Then

File src=((TakesScreenshot)driver).getScreenShotAs(OutputType.FILE);
Files.copy(src,new File("new path/pic.jpeg"));

Plus after Selenium4 you can also take screenshot of webelement as:

WebElement element=driver.findElement(By.xpath("xpath 
 here"));
File src=element.getScreenShotAs(OutputType.FILE);
File.copy(src,new File("new path/pic.jpeg"));

Upvotes: 0

AmitKS
AmitKS

Reputation: 162

Using C# and MSTestframework, Here I have created a static method. Taken a path where I can store the images as jpeg format. to make more clear I am naming those screen shots with current Executing Testcases and date and time of the failure.

          /// <summary>
            /// This method is used to screen shot where test method failed 
            /// </summary>
            /// <param name="testCase">TestCaseName</param>
            public static void Capture(string testCase)
            {
                try
                {
                    StringBuilder path = new StringBuilder("C:/Logs/Screenshot/");
                    Constant.screenshot = ((ITakesScreenshot)Constant.browser).GetScreenshot();
                    string fileName = path.Append(string.Format(testCase + "-at-{0:yyyy-MM dd_hh-mm-ss}.jpeg", DateTime.Now)).ToString();
                    Constant.screenshot.SaveAsFile(fileName, ScreenshotImageFormat.Jpeg);
                }
                catch (Exception e)
                {
                    File.AppendAllText("C:/Logs/FailedTestCasesLogs.txt", "\nCOULD NOT CAPTURE THE SCREENSHOT!\n");
                    Log(e);
                }
    
            }

Upvotes: 0

Vikrant Kumar
Vikrant Kumar

Reputation: 93

/**
 * Take a screenshot and move to the given folder location.
 *
 * @param driver
 * @param folderLocation
 * @return screenShotFilePath
 */
public static String captureScreenshot(WebDriver driver, String folderLocation) {

    // Variable to store screenshot's file path.
    String screenShotFilePath = null;

    // Generate unique id for screen shot name.
    String uniqueId = UUID.randomUUID().toString().substring(31);

    if (driver != null) {

        // Generate screenshot as a file
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // New screenshot file path with having file name
        screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";

        // Move file to the destination location.
        FileUtils.moveFile(scrFile, new File(screenShotFilePath));
    }

    return screenShotFilePath;
}

Upvotes: 1

Du-Lacoste
Du-Lacoste

Reputation: 12757

Yes, it is possible to take screenshots via Selenium WebDriver. I currently use Chrome Driver for snapping images of websites. Please refer the following method captureScreenshot().

You can also add restriction towards web driver, such as

  • use headless version of web browser
  • disable notification when page loads
  • start full screen, etc.

If a website is equipped with Alert Box, your web driver will not be able to capture screenshot since exception will be thrown. In that scenario you need to close the alert box and then get the screenshot. Following code fragment does the closing of alert box.

    public void captureScreenshot() throws InterruptedException, IOException {

        System.out.println("Creating Chrome Driver");

        // Set Chrome Driver
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

        // Add arguments to Chrome Options
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("start-maximized");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--start-fullscreen");
        chromeOptions.addArguments("--disable-extensions");
        chromeOptions.addArguments("--disable-popup-blocking");
        chromeOptions.addArguments("--disable-notifications");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--dns-prefetch-disable");
        chromeOptions.addArguments("enable-automation");
        chromeOptions.addArguments("disable-features=NetworkService");

        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("https://www.google.com");
        System.out.println("Wait a bit for the page to render");
        TimeUnit.SECONDS.sleep(5);
        System.out.println("Taking Screenshot");
        File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String imageDetails = "D:\\Images";
        File screenShot = new File(imageDetails).getAbsoluteFile();
        FileUtils.copyFile(outputFile, screenShot);
        System.out.println("Screenshot saved: {}" + imageDetails);
    }
}

In order to accept Alert Box and Get Screenshot:

String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "D://Images"
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193058

There are multiple methods through Selenium's Java and Python client to take a screenshot using Selenium WebDriver.


Java Methods

The following are the different Java methods to take a screenshot:

  • Using getScreenshotAs() from the TakesScreenshot interface:

  • Code block:

         package screenShot;
    
         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.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         public class Firefox_takesScreenshot {
    
             public static void main(String[] args) throws IOException {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://login.bws.birst.com/login.html/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Birst"));
                 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                 FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Mads_Cruz_screenshot.png"));
                 driver.quit();
             }
         }
    
  • Screenshot:

    Mads_Cruz_screenshot

  • If the webpage is jQuery enabled, you can use from the pazone/ashot library:

  • Code block:

         package screenShot;
    
         import java.io.File;
         import javax.imageio.ImageIO;
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         import ru.yandex.qatools.ashot.AShot;
         import ru.yandex.qatools.ashot.Screenshot;
         import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
    
         public class ashot_CompletePage_Firefox {
    
             public static void main(String[] args) throws Exception {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://jquery.com/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("jQuery"));
                 Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
                 ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/firefoxScreenshot.png"));
                 driver.quit();
             }
         }
    
  • Screenshot:

    firefoxScreenshot.png

  • Using from assertthat/selenium-shutterbug library:

  • Code block:

         package screenShot;
    
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import com.assertthat.selenium_shutterbug.core.Shutterbug;
         import com.assertthat.selenium_shutterbug.utils.web.ScrollStrategy;
    
         public class selenium_shutterbug_fullpage_firefox {
    
             public static void main(String[] args) {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://www.google.co.in");
                 Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("./Screenshots/");
                 driver.quit();
             }
         }
    
  • Screenshot:

    2019_03_12_16_30_35_787.png


Python Methods

The following are the different Python methods to take a screenshot:

  • Using save_screenshot() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.save_screenshot('./Screenshots/save_screenshot_method.png')
         driver.quit()
    
  • Screenshot:

    save_screenshot_method.png

  • Using the get_screenshot_as_file() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.get_screenshot_as_file('./Screenshots/get_screenshot_as_file_method.png')
         driver.quit()
    
  • Screenshot:

    get_screenshot_as_file_method.png

  • Using get_screenshot_as_png() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         screenPnG = driver.get_screenshot_as_png()
    
         # Crop it back to the window size (it may be taller)
         box = (0, 0, 1366, 728)
         im = Image.open(BytesIO(screenPnG))
         region = im.crop(box)
         region.save('./Screenshots/get_screenshot_as_png_method.png', 'PNG', optimize=True, quality=95)
         driver.quit()
    
  • Screenshot:

    get_screenshot_as_png_method.png

Upvotes: 5

Rakesh Raut
Rakesh Raut

Reputation: 183

C# code

IWebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((ITakesScreenshot)driver).GetScreenshotAs(OutputType.FILE);

// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Upvotes: 1

Anuj Teotia
Anuj Teotia

Reputation: 1323

Java

A method to capture a screenshot for the failures in Selenium with TestName and Timestamp appended.

public class Screenshot{
    final static String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
    public static String imgname = null;

    /*
     * Method to Capture Screenshot for the failures in Selenium with TestName and Timestamp appended.
     */
    public static void getSnapShot(WebDriver wb, String testcaseName) throws Exception {
      try {
      String imgpath = System.getProperty("user.dir").concat("\\Screenshot\\"+testcaseName);
      File f = new File(imgpath);
      if(!f.exists())   {
          f.mkdir();
        }
        Date d = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("dd_MM_yy_HH_mm_ss_a");
        String timestamp = sd.format(d);
        imgname = imgpath + "\\" + timestamp + ".png";

        // Snapshot code
        TakesScreenshot snpobj = ((TakesScreenshot)wb);
        File srcfile = snpobj.getScreenshotAs(OutputType.FILE);
        File destFile = new File(imgname);
        FileUtils.copyFile(srcfile, destFile);

      }
      catch(Exception e) {
          e.getMessage();
      }
   }

Upvotes: 2

akhilesh gulati
akhilesh gulati

Reputation: 128

public static void getSnapShot(WebDriver driver, String event) {

    try {
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        BufferedImage originalImage = ImageIO.read(scrFile);
        //int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
        ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
        Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
        jpeg.setAlignment(Image.MIDDLE);
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell1 = new PdfPCell(new Paragraph("\n"+event+"\n"));
        PdfPCell cell2 = new PdfPCell(jpeg, false);
        table.addCell(cell1);
        table.addCell(cell2);
        document.add(table);
        document.add(new Phrase("\n\n"));
        //document.add(new Phrase("\n\n" + event + "\n\n"));
        //document.add(jpeg);
        fileWriter.write("<pre>        " + event + "</pre><br>");
        fileWriter.write("<pre>        " + Calendar.getInstance().getTime() + "</pre><br><br>");
        fileWriter.write("<img src=\".\\img\\" + index + ".jpg\" height=\"460\" width=\"300\"  align=\"middle\"><br><hr><br>");
        ++index;
    }
    catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Mohsin Awan
Mohsin Awan

Reputation: 1172

C#

You can use the following code snippet/function to take screenshot with Selenium:

    public void TakeScreenshot(IWebDriver driver, string path = @"output")
    {
        var cantakescreenshot = (driver as ITakesScreenshot) != null;
        if (!cantakescreenshot)
            return;
        var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
        filename = path + @"\" + filename + ".png";
        var ss = ((ITakesScreenshot)driver).GetScreenshot();
        var screenshot = ss.AsBase64EncodedString;
        byte[] screenshotAsByteArray = ss.AsByteArray;
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        ss.SaveAsFile(filename, ImageFormat.Png);
    }

Upvotes: 2

jotrocken
jotrocken

Reputation: 2333

Robot Framework

Here is a solution using Robot Framework with the Selenium2Library:

*** Settings ***
Library                        Selenium2Library

*** Test Cases ***
Example
    Open Browser               http://localhost:8080/index.html     firefox
    Capture Page Screenshot

This will save a screenshot in the working space. It is also possible to supply a filename to the keyword Capture Page Screenshot to change that behavior.

Upvotes: 1

userlond
userlond

Reputation: 3818

C#

using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;

namespace example.com
{
    class Program
    {
        public static PhantomJSDriver driver;

        public static void Main(string[] args)
        {
            driver = new PhantomJSDriver();
            driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
            driver.Navigate().GoToUrl("http://www.example.com/");
            driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
            driver.Quit();
        }
    }
}

It requires NuGet packages:

  1. PhantomJS 2.0.0
  2. Selenium.Support 2.48.2
  3. Selenium.WebDriver 2.48.2

It was Tested with .NET Framework v4.5.2.

Upvotes: 8

Khaja Mohammed
Khaja Mohammed

Reputation: 779

You can give a try to AShot API. It is on GitHub.

Examples of tests.

Upvotes: 2

djangofan
djangofan

Reputation: 29669

Selenide / Java

Here is how the Selenide project does it, making it easier than just about any other way of doing it:

import static com.codeborne.selenide.Selenide.screenshot;    
screenshot("my_file_name");

For JUnit:

@Rule
public ScreenShooter makeScreenshotOnFailure = 
     ScreenShooter.failedTests().succeededTests();

For TestNG:

import com.codeborne.selenide.testng.ScreenShooter;
@Listeners({ ScreenShooter.class})

Upvotes: 1

Jason Smiley
Jason Smiley

Reputation: 289

Java

I thought I would give my full solution since there are two different ways of getting a screenshot. One is from the local browser, and one is from the remote browser. I even embed the image into the HTML report:

@After()
public void selenium_after_step(Scenario scenario) throws IOException, JSONException {

    if (scenario.isFailed()){

        scenario.write("Current URL = " + driver.getCurrentUrl() + "\n");

        try{
            driver.manage().window().maximize();  // Maximize window to get full screen for chrome
        }
        catch (org.openqa.selenium.WebDriverException e){
            System.out.println(e.getMessage());
        }

        try {
            if(isAlertPresent()){
                Alert alert = getAlertIfPresent();
                alert.accept();
            }
            byte[] screenshot;
            if(false /*Remote Driver flow*/) { // Get a screenshot from the remote driver
                Augmenter augmenter = new Augmenter();
                TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
                screenshot = ts.getScreenshotAs(OutputType.BYTES);
            } 
            else { // Get a screenshot from the local driver
                // Local webdriver user flow
                screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            }
            scenario.embed(screenshot, "image/png"); // Embed the image in reports
        } 
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } 
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }

    //seleniumCleanup();
}

Upvotes: 1

Hemant
Hemant

Reputation: 99

Python

def test_url(self):
    self.driver.get("https://www.google.com/")
    self.driver.save_screenshot("test.jpg")

It will save a screenshot in the same directory the where script is saved.

Upvotes: 2

Bern&#225;t
Bern&#225;t

Reputation: 1391

Selenese

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd

Upvotes: 2

Raghuveer
Raghuveer

Reputation: 115

Java

public void captureScreenShot(String obj) throws IOException {
    File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshotFile, new File("Screenshots\\" + obj + "" + GetTimeStampValue() + ".png"));
}

public String GetTimeStampValue()throws IOException{
    Calendar cal = Calendar.getInstance();
    Date time = cal.getTime();
    String timestamp = time.toString();
    System.out.println(timestamp);
    String systime = timestamp.replace(":", "-");
    System.out.println(systime);
    return systime;
}

Using these two methods you can take a screen shot with the date and time as well.

Upvotes: 2

Yerram Naveen
Yerram Naveen

Reputation: 286

Java

String yourfilepath = "E:\\username\\Selenium_Workspace\\foldername";

// Take a snapshort
File snapshort_file = ((TakesScreenshot) mWebDriver)
        .getScreenshotAs(OutputType.FILE);
// Copy the file into folder

FileUtils.copyFile(snapshort_file, new File(yourfilepath));

Upvotes: 2

Steve HHH
Steve HHH

Reputation: 13147

Java

I could not get the accepted answer to work, but as per the current WebDriver documentation, the following worked fine for me with Java 7 on OS X v10.9 (Mavericks):

import java.io.File;
import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

   public void myTest() throws Exception {
       WebDriver driver = new RemoteWebDriver(
               new URL("http://localhost:4444/wd/hub"),
               DesiredCapabilities.firefox());

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

       // RemoteWebDriver does not implement the TakesScreenshot class
       // if the driver does have the Capabilities to take a screenshot
       // then Augmenter will add the TakesScreenshot methods to the instance
       WebDriver augmentedDriver = new Augmenter().augment(driver);
       File screenshot = ((TakesScreenshot)augmentedDriver).
               getScreenshotAs(OutputType.FILE);
   }
}

Upvotes: 4

Kv.senthilkumar
Kv.senthilkumar

Reputation: 946

Python

You can capture the image from windows using the Python web driver. Use the code below which page need to capture the screenshot.

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')

Upvotes: 1

Related Questions