How to take a screenshot in Selenium WebDriver

 How to take a screenshot in Selenium WebDriver


One of the most useful capabilities of the WebDriver is to take a screen shot when it fails during the execution time and save it to a safe location so that it can be seen later to get to know where the test is failed. By default screenshot capability is enabled in all major browsers. By the way, TakesScreenshot is an interface and is implemented by Firefox, Opera, Chrome, IE Driver
and so on. In three variant formats, WebDriver provides taking screen shot such as BASE64, FILE and BYTES (raw data). If FILE format is chosen, a (dot) png file is used to write the data into it, once the JVM is killed automatically after the session file is deleted unless it is saved in a local or a remote machine.

//take and save screen shot
File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sourceFile, new File("C:\\Users\\Public\\Pictures\\testStartBrowser.png"));

//print out here file is saved
System.out.println("Absolute path is :" + sourceFile.getAbsolutePath());


Notice that preceding code demonstrates screen shot will be stored to the local machine if it fails during the run time as a file format. In Firefox Driver, getScreenshotAs() takes the whole page as a screen shot but in Chrome Driver only takes the visible portion.



To take a screenshot in Python



from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://www.rt.com/')
driver.save_screenshot('rtshot1.png')
driver.quit()







Comments

Popular posts from this blog

Implicitly Wait in Selenium WebDriver

Explicitly Wait in Selenium WebDriver