How to capture a screenshot using Selenium WebDriver?
Experience Level: Medior
Tags: Quality Assurance (QA)Selenium
Answer
To capture screenshot, use the method GetScreenshot() of the Selenium driver. if you are using interface IWebDriver, you will need to cast the driver instance to ITakesScreenshot interface.
C#
try {
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var screenshotFileName = @"C:\Tests\Screenshots\Screenshot.jpg";
screenshot.SaveAsFile(screenshotFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception ex) {
Console.WrieLine(ex.ToString());
}
Note that the code can fail while generationg screenshot or saving the screenshot to a filesystem so it's always a good practice to use try/catch.
Related Selenium job interview questions
What is Object Repository? How can we create Object Repository in Selenium?
Quality Assurance (QA)Selenium JuniorWhat is the difference between Selenium and QTP?
Quality Assurance (QA)Selenium JuniorCan Selenium handle windows based pop up?
Quality Assurance (QA)Selenium JuniorUsing Selenium, when do we use findElement(...) and findElements(...)?
Quality Assurance (QA)Selenium JuniorHow to type text into a textbox using Selenium?
Quality Assurance (QA)Selenium Junior