Hey there! any question in your mind? Ask It Now!.

Popular Categories





how to get screenshot using selenium webdriver.

+2 votes
207 views
asked in Software Testing by tester (1,550 points)

I am running a suite in which we have 10 test cases and each test case has some steps, Now the problem is when a step gets fail I have to add a screenshot in the report, So I want to know how to take screenshot of current window in selenium webdriver.

commented by Mohit
You can use try and catch blocks. Write your test case code in try block and screen shot code in catch block. This way it will take screen shot each time you have failed test case.

1 Answer

0 votes
answered by seleniumGuru Expert (4,570 points)

It's a good way to debug your script by taking screenshot whenever script gets failed.

In selenium webdriver there is a method to take screenshot which is GetScreenshot Method
 

And this is the command to take a screenshot :

Java

File scrFile = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE);

Let me show you the way by which we can use this :

I am using this supporting method in my suite .

public void GetScreenshot(Keyword objKeyword) {

       File scrFile = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE);

       String strScreenshotName = objKeyword.GetScreenshotName() + "_" + System.currentTimeMillis() + ".png";

       objKeyword.SetScreenshotName(strScreenshotName);

       try {

           FileUtils.copyFile(scrFile, new File(this.strScreenshotFolderPath + "/" + strScreenshotName));

       } catch (Throwable ex) {

           log4j.error("Exception thrown while saving the screenshot for keyword " + objKeyword.GetKeyword() + ", Exception is: " + ex.toString());

       }

   }

Here we are giving a dynamic name to the screenshot and saving it to a folder location. I hope you would understand it .

Python

For python the command is :

browser.save_screenshot('screenie.png')  

or

driver.get_screenshot_as_file('/tmp/google.png')

And you can use like this in a sanrio :

from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com/')

driver.get_screenshot_as_file('/tmp/google.png')

browser.quit()

Ruby

For Ruby use this :

require 'rubygems'

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie

driver.get "https://www.google.com"

driver.save_screenshot("./screen.png")

JavaScript

For JS in selenium use this :

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);

});

});

Related Questions

Not a Member yet?

Ask to Folks Login

My Account
333 Folks are online
27 members and 306 guest online
Your feedback is highly appreciated