Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Take a screenshot with Selenium WebDriver

Take A Screenshot With Selenium WebDriver

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

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!

The post Take a screenshot with Selenium WebDriver appeared first on TestingRepository.



This post first appeared on Testing Repository - Creating Testing, please read the originial post: here

Share the post

Take a screenshot with Selenium WebDriver

×

Subscribe to Testing Repository - Creating Testing

Get updates delivered right to your inbox!

Thank you for your subscription

×