How To Take Screenshots In Selenium WebDriver Using JavaScript.

Source

Why take screenshots when running a Selenium test

How to take screenshots in Selenium WebDriver using JavaScript?

Taking screenshots in Selenium JavaScript using the TakeScreenshot interface

driver.takeScreenshot().then(
function(image) {
require('fs').writeFileSync(file, image, encoding_system);
}
);
// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")
// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();
let driver = browser.forBrowser("chrome").build();

driver.get('https://lambdatest.github.io/sample-todo-app/');

driver.findElement(By.name('li1')).click();
driver.findElement(By.name('li2')).click();
driver.findElement(By.id("sampletodotext")).sendKeys("New item");
driver.findElement(By.id("addbutton")).click();

driver.takeScreenshot().then(
function(image) {
require('fs').writeFileSync('captured_image_3.png', image, 'base64');
}
);

driver.quit();
// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")
// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();
let driver = browser.forBrowser("chrome").build();
driver.findElement(By.name('li1')).click();
driver.findElement(By.name(‘li2’)).click();
driver.findElement(By.id(“sampletodotext”)).sendKeys(“New item”);
driver.findElement(By.id(“addbutton”)).click();
driver.takeScreenshot().then(
function(image) {
require('fs').writeFileSync('captured_image_3.png', image, 'base64');
}
);
driver.quit();
node take_screenshot_implementation.js
// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")

// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();
let driver = browser.forBrowser("chrome").build();

(async function () {

// Navigate to the required URL
driver.get('');

// Press the Get New User button
driver.findElement(By.id('save')).click();

// Wait for 5 secs to let the dynamic content to load
await driver.sleep(5000);

// Take screenshot of the application with the dynamic content
driver.takeScreenshot().then(
function (image) {
require('fs').writeFileSync('screenshot_with_wait.png', image, 'base64')
});

// Exit the driver
driver.quit();

}());
// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")
// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();
let driver = browser.forBrowser("chrome").build();
// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")

// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();
let driver = browser.forBrowser("chrome").build();

(async function () {

// Navigate to the required URL
driver.get('');

// Press the Get New User button
driver.findElement(By.id('save')).click();

// Wait for 5 secs to let the dynamic content to load
await driver.sleep(5000);

// Take screenshot of the application with the dynamic content
driver.takeScreenshot().then(
function (image) {
require('fs').writeFileSync('screenshot_with_wait.png', image, 'base64')
});

// Exit the driver
driver.quit();

}());
// Navigate to the required URL
driver.get('');
// Press the Get New User button
driver.findElement(By.id('save')).click();
// Wait for 5 secs to let the dynamic content to load
await driver.sleep(5000);
// Take screenshot of the application with the dynamic content
driver.takeScreenshot().then(
function (image) {
require('fs').writeFileSync('screenshot_with_wait.png', image, 'base64')
});
driver.quit();
node take_screenshot_implementation2.js

Taking screenshots of a particular element in Selenium JavaScript

const sharp = require('sharp')

// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")
// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();
let driver = browser.forBrowser("chrome").build();

driver.get('https://lambdatest.github.io/sample-todo-app/');

driver.findElement(By.id("sampletodotext")).sendKeys("New item");
driver.findElement(By.id("addbutton")).click();

driver.takeScreenshot().then(
function (image) {
require('fs').writeFileSync('image_viewable_full.png', image, 'base64')
});

try {

var _height = 0, _width = 0, _left = 0, _top = 0;

driver.findElement(By.xpath('/html/body/div/div/div/ul/li[6]'))
.getLocation().then(location => {
_left = location.x;
_top = location.y;
});
driver.findElement(By.xpath('/html/body/div/div/div/ul/li[6]'))
.getSize().then(size => {
_width = size.width;
_height = size.height;
});


(async function () {

await driver.sleep(5000);

sharp('image_li6.png')
.extract({ left: parseInt(_left), top: parseInt(_top), width: parseInt(_width), height: parseInt(_height) })
.toFile('image_li6_crop.png')
.then(function (new_file_info) {
console.log("Image cropped and saved");
})
.catch(function (err) {
if (err) console.log(err);
});

}());
}
catch (err) {
console.log("Error: " + err);
};
driver.quit();
// Include the chrome driver
require("chromedriver");
require("selenium-webdriver")
// Include selenium webdriver
let webdriver = require("selenium-webdriver");
var By = require("selenium-webdriver").By;
let browser = new webdriver.Builder();let driver = browser.forBrowser(“chrome”).build();
driver.get(‘https://lambdatest.github.io/sample-todo-app/');
driver.findElement(By.id(“sampletodotext”)).sendKeys(“New item”);
driver.findElement(By.id(“addbutton”)).click();
driver.takeScreenshot().then(
function (image) {
require('fs').writeFileSync('image_viewable_full.png', image, 'base64')
});
var _height = 0, _width = 0, _left = 0, _top = 0;
driver.findElement(By.xpath('/html/body/div/div/div/ul/li[6]'))
.getLocation().then(location => {
_left = location.x;
_top = location.y;
});
driver.findElement(By.xpath('/html/body/div/div/div/ul/li[6]'))
.getSize().then(size => {
_width = size.width;
_height = size.height;
});
sharp('image_element_li6.png')
.extract({ left: parseInt(_left), top: parseInt(_top), width: parseInt(_width), height: parseInt(_height) })
.toFile('image_li6_crop.png')
.then(function (new_file_info) {
console.log("Image cropped and saved");
})
.catch(function (err) {
if (err) console.log(err);
});
driver.quit();

How to take screenshot of a particular WebElement using Selenium 4 and JavaScript

const {By,Key,Builder} = require("selenium-webdriver");
require("chromedriver");

let fs = require('fs');

async function WebElementCapture(){
//To wait for browser to build and launch properly
let driver = await new Builder().forBrowser("chrome").build();

//To fetch https://lambdatest.github.io/sample-todo-app/ from the browser with our code.
await driver.get("https://lambdatest.github.io/sample-todo-app/");

//Add a new item in the list
await driver.findElement(By.id("sampletodotext")).sendKeys("Add a new item in the list");
await driver.findElement(By.id("addbutton")).click();

let ele = await driver.findElement(By.xpath('/html/body/div/div/div/ul/li[6]'));

//Capture the element screenshot
let encodedString = await ele.takeScreenshot(true);
await fs.writeFileSync('./image_li6_crop.png', encodedString, 'base64');
await driver.quit();
}
WebElementCapture()
await driver.findElement(By.id("sampletodotext")).sendKeys("Add a new item in the list");
await driver.findElement(By.id("addbutton")).click();
let ele = await driver.findElement(By.xpath('/html/body/div/div/div/ul/li[6]'));
let encodedString = await ele.takeScreenshot(true);
await fs.writeFileSync('./image_li6_crop.png', encodedString, 'base64');

Taking screenshots step-by-step in Selenium WebDriver JavaScript using LambdaTest

How to capture screenshots step-by-step on LambdaTest

capabilities = {
'build': ’Capture Screenshots’, //Build name
'name': 'Your Test Name', // Test name
'platform':'MacOS Big sur', // OS name
'browserName': 'Firefox', // Browser name
'version': '89.0', // Browser version
"resolution" : "1280x960",

'visual': true, // To take step by step screenshot

'network':false, // To capture network Logs
'console':false, // To capture console logs.
'tunnel': false // If you want to run the localhost then change it to true
};
String gridURL = “http://” + username + “:” + accesskey + “@hub.lambdatest.com/wd/hub”;
var capabilities = {
"build" : "your build name",
"name" : "your test name",
"platform" : "'MacOS Big sur",
"browserName" : "Firefox",
"version" : "89.0",
"visual" : true
}
LT_USERNAME = "username";
LT_ACCESS_KEY = "access key";

caps = {
'build': 'Capture Screenshots', //Build name
'name': 'Your Test Name', // Test name
'platform':'MacOS Big sur', // OS name
'browserName': 'Firefox', // Browser name
'version': '89.0', // Browser version
"resolution" : "1280x960",
'visual': true, // To take step by step screenshot
'network':false, // To capture network Logs
'console':false, // To capture console logs.
'tunnel': false // If you want to run the localhost then change it to true
};

var buildDriver = function () {
return new webdriver.Builder()
.usingServer(
"http://" +
LT_USERNAME +
":" +
LT_ACCESS_KEY +
"@hub.lambdatest.com/wd/hub"
)
.withCapabilities(caps)
.build();
};
LT_USERNAME = "username";
LT_ACCESS_KEY = "access key";

exports.capabilities = {
'build': 'Capture Screenshots', //Build name
'name': 'Your Test Name', // Test name
'platform':'MacOS Big sur', // OS name
'browserName': 'Firefox', // Browser name
'version': '89.0', // Browser version
"resolution" : "1280x960",
'visual': false, // To take step by step screenshot
'network':false, // To capture network Logs
'console':false, // To capture console logs.
'tunnel': false // If you want to run the localhost then change it to true
};
var By = require("selenium-webdriver").By;

var assert = require("assert"),
webdriver = require("selenium-webdriver"),
conf_file = process.argv[3] || "conf/single.conf.js";

var caps = require("../" + conf_file).capabilities;

var buildDriver = function (caps) {
return new webdriver.Builder()
.usingServer(
"http://" +
LT_USERNAME +
":" +
LT_ACCESS_KEY +
"@hub.lambdatest.com/wd/hub"
)
.withCapabilities(caps)
.build();
};

describe("Capture Screenshot " + caps.browserName, function () {
var driver;
this.timeout(0);

beforeEach(function (done) {
caps.name = this.currentTest.title;
driver = buildDriver(caps);
done();
});

it("Take Screenshot JavaScript", function (done) {

driver.get('https://lambdatest.github.io/sample-todo-app/');

driver.findElement(By.name('li1')).click();
driver.findElement(By.name('li2')).click();
driver.findElement(By.id("sampletodotext")).sendKeys("New item");
driver.findElement(By.id("addbutton")).click();
});

afterEach(function (done) {
if (this.currentTest.isPassed) {
driver.executeScript("lambda-status=passed");
} else {
driver.executeScript("lambda-status=failed");
}
driver.quit().then(function () {
done();
});
});
});

How to view screenshots step-by-step on LambdaTest?

Conclusion

Source

--

--

--

I am a Computer Science Engineer by degree, and a Digital Marketer by heart who works at LambdaTest. A social media maven!!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Writer of the Week: Brunette girl

Basic Concept About React.js

How to run Javascript code in a background service on Android

Merge Sort in JavaScript

Quick, I MUST bootstrap something with TypeScript!

RabbitMQ | Dynamic Queue and Consumer | Grails 2.X

Angular Material Dark theme

React Native in Typescript: The proper way to transfer props

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Praveen Mishra

Praveen Mishra

I am a Computer Science Engineer by degree, and a Digital Marketer by heart who works at LambdaTest. A social media maven!!

More from Medium

How To Use Breakpoints For Debugging In Selenium WebDriver

How To Install & Create Your First Test With Cypress.io

AMA: How to print rest assured logs in the terminal?

Cypress VS Selenium