Take a screenshot with Selenium WebDriver


643
1 comment, 643 points
take screenshots in selenium
take screenshots in selenium

Take a screenshot with Selenium WebDriver

Screenshots might give you a  really useful information when you are trying to debug your tests. Here is how to take screenshots in selenium webdriver. First of all It depends when do you want to take the screenshot , that’s on you , I prefer to take screenshots only in case of failure. Inside your hooks file into After statement you need the following piece of code:

Take screenshots in using ruby capybara

After do |scenario|

  if scenario.failed?
    # create output folder if doesn't exist
    Dir::mkdir('output', 0777) if not File.directory?('output')
    # create screenshots if doesn't exist
    Dir::mkdir('output/screenshots', 0777) if not File.directory?('output/screenshots')
    # define your image name
    screenshot = "./output/screenshots/FAILED_#{scenario.name.gsub(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}.png"
    if page.driver.browser.respond_to?(:save_screenshot) then
      page.driver.browser.save_screenshot(screenshot)
    else
      save_screenshot(screenshot)
    end
    FileUtils.chmod(0777, screenshot)
    embed current_url, 'text/plain', current_url
    embed screenshot, 'image/png', ' Screenshot'
  end
end

Take screenshots in selenium webdriver

Here is how you can take screenshots in selenium using Java bindings or c# bindings:

 

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("filepath"));

C#

try
    {            
        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile(@"path/SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }

 

Screenshots can really help you when you analyse your test failures

Advertisements

If you are using reports tools such as reportportal you don’t really have to worry about taking screenshots in case of failure because reportportal will take care of that and will automatically attach the image to the failure.

Also you should know that chromedriver doesn’t support to take screenshots for the entire page , at some point I wrote a pice o code in C# , I will share it with you in a separate post.

Happy Testing!


Like it? Share with your friends!

643
1 comment, 643 points
Test engineer

One Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.