13

What is the correct way of taking a screenshot when running a webdriver test with Selenium's webdriverjs?

I have the stand-alone selenium server started and I can see the command for taking screenshot is logged on the selenium-server, but the screenshot is not being saved.

My code is the following:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().usingServer('http://localURL:4444/wd/hub').withCapabilities({'browserName': 'chrome'}).build();
driver.get([URL to webserver on my local machine])

driver.takeScreenshot("c:\\selenium_local_map\\out1.png");
oberlies
  • 11,503
  • 4
  • 63
  • 110
user2261673
  • 145
  • 2
  • 7

1 Answers1

24

Take screenshot returns a promise that will resolve with a Base64 encoded png. To write the data, you'll need to do something like the following:

function writeScreenshot(data, name) {
  name = name || 'ss.png';
  var screenshotPath = 'C:\\selenium_local_map\\';
  fs.writeFileSync(screenshotPath + name, data, 'base64');
};

driver.takeScreenshot().then(function(data) {
  writeScreenshot(data, 'out1.png');
});

More documentation can be found here

HMR
  • 37,593
  • 24
  • 91
  • 160
Ryan
  • 2,460
  • 1
  • 21
  • 22
  • 5
    This is awesome, thank you! Just wanted to add for fellow Node n00bs who are going to copy and paste this then wonder what to do about the resulting error - add the following to line 2: var fs = require('fs'); – kjc26ster May 02 '14 at 00:18
  • 1
    For this code to work, you need to include the following line: var fs = require('fs'); I spent some time trying to find out what that "fs" was about. you have to install the package then this solution will work: _italic_ npm install fs _italic_ – Helio Gabrenha Jr Jan 13 '16 at 18:49
  • Node.js includes the fs module. You just need to require it, not install it separately. – Adriana Jan 12 '21 at 09:03