Skip to main content

Take Screenshots

Take screenshots at different points in your Selenium test

You can take screenshots of your Selenium test in the following two ways:

  1. Using the Visual Logs capability, BrowserStack Automate can automatically take screenshots during the test run
  2. Explicitly from your test script as and when required and download the screenshot to your local machine

Automatically capture screenshots

BrowserStack has a Visual Logs feature to take screenshots automatically during your Selenium test without you initiating a screenshot explicitly through test code.

Note: Visual Logs would be visible in the Automate dashboard only. If you want to download the screenshots to your local machine, then please take a screenshot explicitly from your test script.

These contain the screenshots that are auto-generated during each Selenium command that your code executes. Visual logs help with debugging the exact step and how the page was rendered when the failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.

Visual logs are disabled by default. You can enable them by using the browserstack.debug capability.

Capability Description Expected values
browserstack.debug Enable visual logs A string. Defaults to false

true if you want to enable the visual logs. false otherwise.

For example, this is how you enable visual logs:

// Enabling visual logs

DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserstack.debug", "true");
// Enabling visual logs

var capabilities = {
 "browserstack.debug" : "true"
}
// Enabling visual logs

DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("browserstack.debug", "true");
# Enabling visual logs

$caps = array(
 "browserstack.debug" => "true"
);
# Enabling visual logs

capabilities = {
 "browserstack.debug" : "true"
}
# Enabling visual logs

caps = Selenium::WebDriver::Remote::Capabilities.new
caps["browserstack.debug"] = "true"
# Enabling visual logs

my $capabilities = {
 "browserstack.debug" => "true"
}

Take screenshot from test script explicitly

You can choose to take a screenshot from your test script and either save it to your local machine or only display it in session’s text logs:

Take screenshot and download it to your local machine

You can choose when to take a screenshot from your test script and also save these screenshots to the machine that runs the automated tests. If you are on a CI/CD setup, make sure you transfer these screenshots before you wind down the machine.

Here is how you take a screenshot and save it to your machine:

// Import the relevant packages

// ... your test code

// Take a screenshot and save it to /location/to/screenshot.png

driver = (RemoteWebDriver) new Augmenter().augment(driver);
File srcFile = (File) ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileHandler.copy(srcFile, new File("/location/to/screenshot.png"));

// ... your test code
var fs = require('fs');

webdriver.WebDriver.prototype.saveScreenshot = function(filename) {
  return driver.takeScreenshot().then(function(data) {
      fs.writeFile(filename, data.replace(/^data:image\/png;base64,/,''), 'base64', function(err) {
          if(err) throw err;
      });
  })
};

driver.saveScreenshot('snapshot1.png')
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace SeleniumTest
{
    public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
    {
        public ScreenShotRemoteWebDriver(Uri uri, OpenQA.Selenium.Chrome.ChromeOptions dc)
          : base(uri, dc)
        {
        }

        public new Screenshot GetScreenshot()
        {
            Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
            string base64 = screenshotResponse.Value.ToString();
            return new Screenshot(base64);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ScreenShotRemoteWebDriver driver;
            //IWebDriver driver;
            OpenQA.Selenium.Chrome.ChromeOptions capability = new OpenQA.Selenium.Chrome.ChromeOptions();
            capability.AddAdditionalCapability("os_version", "10", true);
            capability.AddAdditionalCapability("resolution", "1920x1080", true);
            capability.AddAdditionalCapability("browser", "Chrome", true);
            capability.AddAdditionalCapability("browser_version", "latest-beta", true);
            capability.AddAdditionalCapability("os", "Windows", true);
            capability.AddAdditionalCapability("name", "Take Screenshot Sample Test", true); // test name
            capability.AddAdditionalCapability("build", "Screenshot Test Build", true); // CI/CD job or build name
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);
            driver = new ScreenShotRemoteWebDriver(
                new Uri("https://hub-cloud.browserstack.com/wd/hub/"), capability
                );
            driver.Navigate().GoToUrl("https://www.google.com/ncr");
            Console.WriteLine(driver.Title);

            IWebElement query = driver.FindElement(By.Name("q"));
            query.SendKeys("Browserstack");
            query.Submit();
            Console.WriteLine(driver.Title);

            ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
            Screenshot screenshot = screenshotDriver.GetScreenshot();
            screenshot.SaveAsFile("/your/full/screenshot/path/ss.png", OpenQA.Selenium.ScreenshotImageFormat.Png);

            driver.Quit();
        }
    }
}

file_put_contents('screenshot.png', $web_driver->takeScreenshot());
driver.save_screenshot('screenshots.png')
driver.save_screenshot("screenshots.png")
open(FH,'>','screenshot.png');
binmode FH;
my $png_base64 = $driver->screenshot();
print FH MIME::Base64::decode_base64($png_base64);
close FH;

Take screenshot and dispaly it on session’s text logs

You can choose when to take a screenshot from your test script and only display them in the session’s text logs.

Here is how you take a screenshot and show it in text logs:

// Sample test in Java to run Automate session.
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;
import org.openqa.selenium.OutputType;
import java.net.URL;
public class camera {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_ACCESS_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_ACCESS_KEY + "@hub-cloud.browserstack.com/wd/hub";
  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("os_version", "10");
    caps.setCapability("resolution", "1920x1080");
    caps.setCapability("browser", "Chrome");
    caps.setCapability("browser_version", "88.0");
    caps.setCapability("os", "Windows");
    caps.setCapability("name", "BStack-[Java] Sample Test"); // test name
    caps.setCapability("build", "BStack Build Number 1"); // CI/CD job or build name
    WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
    driver = (RemoteWebDriver) new Augmenter().augment(driver);
    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    driver.get("https://www.google.com");
    driver.quit();
  }
}
const webdriver = require('selenium-webdriver');
const fs = require('fs');
// Input capabilities
const capabilities = {
  'browserName' : 'Chrome',
  'browser_version' : '88.0',
  'os' : 'Windows',
  'os_version' : '10',
  'name': 'BStack-[NodeJS] Sample Test', // test name
  'build': 'BStack Build Number 1' // CI/CD job or build name
}
async function runTestWithCaps () {
  let driver = new webdriver.Builder()
    .usingServer('http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub')
    .withCapabilities(capabilities)
    .build();
  await driver.get("http://www.google.com");
  await driver.takeScreenshot()
  await driver.quit();
}
runTestWithCaps();  
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace SeleniumTest
{
    public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
    {
        public ScreenShotRemoteWebDriver(Uri uri, OpenQA.Selenium.Chrome.ChromeOptions dc)
          : base(uri, dc)
        {
        }

        public new Screenshot GetScreenshot()
        {
            Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
            string base64 = screenshotResponse.Value.ToString();
            return new Screenshot(base64);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ScreenShotRemoteWebDriver driver;
            //IWebDriver driver;
            OpenQA.Selenium.Chrome.ChromeOptions capability = new OpenQA.Selenium.Chrome.ChromeOptions();
            capability.AddAdditionalCapability("os_version", "10", true);
            capability.AddAdditionalCapability("resolution", "1920x1080", true);
            capability.AddAdditionalCapability("browser", "Chrome", true);
            capability.AddAdditionalCapability("browser_version", "latest-beta", true);
            capability.AddAdditionalCapability("os", "Windows", true);
            capability.AddAdditionalCapability("name", "Take Screenshot Sample Test", true); // test name
            capability.AddAdditionalCapability("build", "Screenshot Test Build", true); // CI/CD job or build name
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);
            driver = new ScreenShotRemoteWebDriver(
                new Uri("https://hub-cloud.browserstack.com/wd/hub/"), capability
                );
            driver.Navigate().GoToUrl("https://www.google.com/ncr");
            Console.WriteLine(driver.Title);

            IWebElement query = driver.FindElement(By.Name("q"));
            query.SendKeys("Browserstack");
            query.Submit();
            Console.WriteLine(driver.Title);

            ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
            Screenshot screenshot = screenshotDriver.GetScreenshot();

            driver.Quit();
        }
    }
}
<?php
  require_once('vendor/autoload.php');
  use Facebook\WebDriver\Remote\RemoteWebDriver;
  use Facebook\WebDriver\WebDriverBy;
  $caps = array(
    "browser" => "Chrome",
    "browser_version" => "88.0",
    "realMobile" => "true",
    "os" => "Windows",
    "os_version" => "10",
    "name" => "BStack-[Php] Sample Test", // test name
    "build" => "BStack Build Number 1" // CI/CD job or build name
  );
  $web_driver = RemoteWebDriver::create(
    "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
    $caps
  );
  # Searching for 'BrowserStack' on google.com
  $web_driver->get("http://google.com");
  file_put_contents('screenshot.png', $web_driver->takeScreenshot());
  $web_driver->quit();
?>
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
desired_cap = {
 'browser': 'Chrome',
 'browser_version': '88.0',
 'os': 'Windows',
 'os_version': '10',
 'name': 'BStack-[Python] Sample Test', # test name
 'build': 'BStack Build Number 1' # CI/CD job or build name
}
driver = webdriver.Remote(
    command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub',
    desired_capabilities=desired_cap)
driver.get("https://www.google.com")
driver.save_screenshot('screenshots.png')
driver.quit()
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['browser'] = 'Chrome'
caps['browser_version'] = '88.0'
caps['name'] = 'BStack-[Ruby] Sample Test' # test name
caps['build'] = 'BStack Build Number 1' # CI/CD job or build name
driver = Selenium::WebDriver.for(:remote,
  :url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
  :desired_capabilities => caps)
# Searching for 'BrowserStack' on google.com
driver.navigate.to "http://www.google.com"
driver.save_screenshot("screenshots.png")
driver.quit
use Selenium::Remote::Driver;
#Input capabilities
my $extraCaps = {
  'browserName' => 'Chrome',
  'browser_version' => '88.0',
  'os' => 'Windows',
  'os_version' => '10',
  'name' => 'BStack-[Perl] Sample Test', # test name
  'build' => 'BStack Build Number 1' # CI/CD job or build name
};
my $login = "YOUR_USERNAME";
my $key = "YOUR_ACCESS_KEY";
my $host = "$login:$key\@hub-cloud.browserstack.com";
my $driver = new Selenium::Remote::Driver('remote_server_addr' => $host,
  'port' => '80', 'extra_capabilities' => $extraCaps);
# Searching for 'BrowserStack' on google.com
$driver->get('http://www.google.com');
open(FH,'>','screenshot.png');
binmode FH;
my $png_base64 = $driver->screenshot();
print FH MIME::Base64::decode_base64($png_base64);
close FH;
$driver->quit(); 	

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Talk to an Expert