Rectangle 27 1

Take a screenshot with Selenium WebDriver?


public function takescreenshot($event)
  {
    $errorFolder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "ErrorScreenshot";

    if(!file_exists($errorFolder)){
      mkdir($errorFolder);
    }

    if (4 === $event->getResult()) {
      $driver = $this->getSession()->getDriver();
      $screenshot = $driver->getWebDriverSession()->screenshot();
      file_put_contents($errorFolder . DIRECTORY_SEPARATOR . 'Error_' .  time() . '.png', base64_decode($screenshot));
    }
  }

in the current version of facebook/webdriver the method is takeScreenshot() and it is not necessary to base64_encode() the output before saving the file.

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie 
driver.get "https://www.google.com"   
driver.save_screenshot("./screen.png")

Full page is taken by default. At least using headless and Firefox

Is there any way to take the full page screenshot, not just the visible area?

Worked fine for me using Selenium Grid 2. Script and hub running on OS X Snow Leopard; node running on RedHat EL 4 with Firefox 3.6.18 under Xvfb.

more file types and options are available and you can see them in takes_screenshot.rb

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


public void TakeScreenshot()
{
    try
    {            
        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }
}

It will only get what is in the scope of the driver, this is to allow multiple parallel tests taking place. Note that it will not zoom out if your driver's main window focus has a scrollbar or if it exceeds a single page.

Works perfectly. Caveat: takes a screen shot not a page shot.

do you mean it gets desktop and everything? Or you mean that it just gets the viewport?

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


driver.takeScreenshot().then(function(data){
   var base64Data = data.replace(/^data:image\/png;base64,/,"")
   fs.writeFile("out.png", base64Data, 'base64', function(err) {
        if(err) console.log(err);
   });
});

@JohnDemetriou, data is the name of the object or variable that will be created when you call it. U can call it var1 if you wish. U should look at takeScreenshot() function to know what exactly it is. Maybe a binary image rendered from javascript using canvas. It can be the dom, before it's rendered. Look into.

in data.replace what exactly are you doing in the parenthesis?

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
browser.quit()

Confusingly, a .get_screenshot_as_file(filename) method also exists that does the same thing.

Each WebDriver has a .save_screenshot(filename) method. So for Firefox, it can be used like this:

For other browsers, exchange the webdriver instance. If you just want screenshots of your website including state, have a look at Usersnap.

There are also methods for: .get_screenshot_as_base64() (for embedding in html) and .get_screenshot_as_png()(for retrieving binary data).

To make a scrennshot of a full page, not only the visible area, use my python code from my answer here to stich: stackoverflow.com/questions/37906704/

Unfortunately this does not seem to work on a grid system.

and Note that WebElements have a .screenshot() method that works similarly, but only captures the selected element.

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


HtmlUnitDriver
TakesScreenshot
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)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"));
org.apache.commons.io.FileUtils

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Copying the file, rather than renaming it, is a good idea if there is any chance that the source and destination might not be on the same filesystem. You can't rename across filesystem boundaries (on unix, at least). Note that it's common for /tmp to be on its own filesystem, and FirefoxDriver writes screenshots to /tmp.

Is there a way to do it only for failed cases?

Yes, it is possible. The following example is in Java:

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


WebDriver augmentedDriver = new Augmenter().augment(driver); 
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way

I got this issue resolved. You can augment the RemoteWebDriver to give it all of the interfaces its proxied driver implements:

If you do that, then don't you need to copy screenshots to a filename with threadId so that you can tell which threads/instances of your driver threw the screenshot? Otherwise, multiple instances of a browser on one grid node would overwrite each others screenshots?

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


public void takeScreenshotElement(WebElement element) throws IOException {
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("//path//to");
    FileUtils.copyFile(screenshot, file);
}

Did you try the code? It worked when I last tried it.

I don't think this approach actual can work, as the the screenshot and the actual browser have different resolutions. So when using the coordinate location obtained by selenium on your image you're pretty sure to run into a java.awt.image.RasterFormatException: (y + height) is outside of Raster

In Firefox works fine as it crops the element screen from full Image based on Dimensions. In Chrome if the element is available in view portion with out scrolling the from that view portion image it captures element fine. If we want to take screenshot after scrolling document.documentElement.clientHeight two times of client Height the use (location.y)-2*clientHeight to get exact element screenshot. Thanks for this post as it helps me...

It works perfectly fine as long as you try capturing an element which is visible without scrolling. When you need to scroll to an element to capture it, then the y offset is calculated from the top of the page, which then exceeds the boundaries of the full-screen image. So the easiest solution is to either increase the screen size code this.driver.manage().window().setSize(new Dimension(1680, 1050)); or to remove any non required elements via css. The proper solution would be to calculate the y-offset from scrolling.

Seems to be missing here - taking screenshot of a specific element in Java:

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
    ...
    public function screenshot($filepath) {
        $filedata = $this->currentScreenshot();
        file_put_contents($filepath, $filedata);
    }

    public function testSomething() {          
        $this->screenshot('/path/to/screenshot.png');
    }
    ...
}

daaaamn! I wanna know more about this, Selenium is new to me and I'm looking for a cli solution to creating screenshots across a number of browsers and OSes to do visual tests

Note
Rectangle 27 1

Take a screenshot with Selenium WebDriver?


public Bitmap TakeScreenshot(By by) {
    // 1. Make screenshot of all screen
    var screenshotDriver = _selenium as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}
Note