top of page

How to take screenshots via Selenium.

  • Writer: khyati sehgal
    khyati sehgal
  • Oct 1, 2015
  • 1 min read

If we have to prove something to either a developer or a Product owner then we generally we have several ways via which we can actually show the idea to them, but what if whatever you want to show stop working when you actually want to demo it? This is silly, right? But it happens, You have to believe me!!

So for such circumstances we search for back up which will show what exactly we want to show. And that’s where we require screen shot, there could be other reasons as well, I am Sure there are.. but the major is to give other person a clear picture of what happened and how? Selenium also provides certain features via which we can take screen shots of the tests here is the small code to do it.

public static void main(String a[]) throws InterruptedException { WebDriver driver = new FirefoxDriver(); try { driver.get("http://www.google.com"); WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("WebDriver API"); WebElement searchButton = driver.findElement(By.name("btnG")); searchButton.click(); Thread.sleep(2000); System.out.println("What's the current Url: " + driver.getCurrentUrl()); File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("c:\\googlesearch-webdriverapi.png")); driver.close(); } catch (Exception e) { e.printStackTrace(); // For debugging purposes } } Lets analyze the code more:- Go to Google Home Page, or open an  URL.

Look for search textbox and enter search term there

WebElement searchBox = driver.findElement(By.name(“q”));

This is not required or recommended any where, but just wait for the last click() operation to get completed fine.

Thread.sleep(2000);

If you wish to take screen shot of this page, you can!

File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(“c:\\googlesearch-webdriverapi.png”));

Close the driver, once you’re done.

driver.close();

Comentários


bottom of page