Take Screenshot with Selenium Webdriver

By | 14/09/2015

You can take screenshot of browser with browser.

Python:

you can use get_screenshot_as_file(path_to_save).

# -*- coding: UTF-8 -*-
import unittest
from selenium import webdriver

class TestClass(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
    
    def test_MahsumAkbasNet_Pass(self):
        
        self.driver.get("http://www.mahsumakbas.net/selenium")
        
        self.driver.save_screenshot("D:\\python_selenium_screenshot.jpg")
        
    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

There is wrapper function around that is save_screenshot(). also, you can take screenshot as binary by get_screenshot_as_png() and you can get the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML by get_screenshot_as_base64() function

Java:

you can use getScreenshotAs(arg0) function

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;

public class Screenshot  {
    static WebDriver driver = new FirefoxDriver();
    public static void main(String[] args) throws IOException {

        driver.get("http://www.mahsumakbas.net/selenium");        
        
        File scrSht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        
        FileUtils.copyFile(scrSht, new File("D:\\JavaSeleniumScreenshot.jpg"));
        
        driver.quit();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*