How to get a screenshot of a full web page using Selenium and Java?

How to take a screenshot of the entire web page (full screenshot), and not only partially (top to bottom) using Selenium WebDriver?

My code: (Java bindings)

System.setProperty("webdriver.chrome.driver","/home/alex/Downloads/chromedriver_linux64/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("http://google.com"); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(RESULT_FILENAME)); 

Any ideas on how to handle this?

+10
source share
7 answers

LE: I see that quite a lot of people are interested in screenshots on the whole page, so I thought that I could update the answer with some positive points (silver bullets).

There are quite a few web testing frameworks that can (with minimal settings and effort) create a complete screenshot . I am from NodeJS testing environment, so I can only confirm the following: WebdriverIO and Google Puppeteer .

If anyone is interested in an easy way to do this with WebdriverIO, check this answer.


The short answer is NO, YOU CAN'T if you are using only Selenium (detailed explanation below). But what you can do is make most of the (monitor) of your device viewport .

So, launch your browser instance (driver) using ChromeOptions() , which is a method to configure the capabilities of ChromeDriver. We can do the following:

  • maximize window (using --start-maximized );
  • switch to full screen mode ( F11 -key on Windows, Control+Cmd+F on Mac, using the switch --start-fullscreen ).
  • Note: A complete list of Chrome command line switches can be found here .

Your code should look like this:

 // Setting your Chrome options (Desired capabilities) ChromeOptions options = new ChromeOptions(); options.add_argument('--start-maximized'); options.add_argument('--start-fullscreen'); // Creating a driver instance with the previous capabilities WebDriver driver = new ChromeDriver(options); // Load page & take screenshot of full-screen page driver.get("http://google.com"); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 

Now, with regard to the problem with the full page, all drivers ( chromedriver , geckodriver , IEDriver , EdgeDriver , etc.) EdgeDriver standard WebDriver W3C . Thus, they depend on how the WebDriver team wants to show the functionality of the various functions, in our case, β€œScreenshot” .

If you read the definition, it clearly states the following:

The Take Screenshot command takes a screenshot of the VIEWPORT top-level viewing contexts.

Outdated versions, some drivers could take a screenshot of the entire page (more on this here ), for example, the old FirefoxDriver, IEDriver, etc. This is no longer the case, as they all now implement the (literally) WebDriver W3C Standard.

+14
source

I found the tutorial http://www.softwaretestingmaterial.com/how-to-capture-full-page-screenshot-using-selenium-webdriver/ For maven users: remember to add the dependency with https://mvnrepository.com/artifact/ ru.yandex.ru.qatools.ashot / ashot When I tested this script, I had large pictures that could not be opened in the browser (too large or broken).

So maybe someone knows some script where the focus page is on the last locator used?

+5
source

This article seems to suggest AShot is working for me. In addition, I have successfully implemented a full screenshot of the page in a Cucumber report with the following code

  scenario.embed(takeScreenShotAsByte(getWebDriver()), "image/png"); private static byte[] takeScreenShotAsByte(WebDriver webDriver) throws IOException { return takeFullPageScreenShotAsByte(webDriver); } private static byte[] takeFullPageScreenShotAsByte(WebDriver webDriver) throws IOException { Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)) .takeScreenshot(webDriver); BufferedImage originalImage = fpScreenshot.getImage(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(originalImage, "png", baos); baos.flush(); return baos.toByteArray(); } } 
+2
source

For some pages, I take a screenshot from the beginning and end of the page. Therefore, I use two screenshots:

 public static String javaIoTmpDir = System.getProperty("java.io.tmpdir"); //tmp dir //create screenshot driver.manage().window().fullscreen(); //For large pages - body over 850 px highh - take addition screenshot of the end of page if (driver.findElements(By.id("panel_body")).size()>0) { WebElement body = driver.findElement(By.id("panel_body")); int bodyHight = body.getSize().getHeight(); if (bodyHight > 850) { Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_END); robot.keyRelease(KeyEvent.VK_END); Thread.sleep(1000); File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); String timePictureEnd = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png"; FileUtils.copyFile(scrFile, new File(timePictureEnd)); robot.keyPress(KeyEvent.VK_HOME); //back to top page for next screen robot.keyRelease(KeyEvent.VK_HOME); Thread.sleep(1000); } } String timePicture = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png"; File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(timePicture)); 
+1
source

You can use Phantomjs to achieve this.

Here is my Java code:

 public class PhantomjsTest { public static void main(String[] args) { try { long start=System.currentTimeMillis(); //The page you want to screenshot String targetUrl="https://www.iqiyi.com/"; //File path String targetImg="iqiyi.png"; String command = "/Users/hetiantian/SoftWares/phantomjs/bin/phantomjs /Users/hetiantian/SoftWares/phantomjs/examples/rasterize.js "+targetUrl + " " +targetImg; Process p = Runtime.getRuntime().exec(command); p.waitFor(); System.out.println((System.currentTimeMillis()-start)); } catch (Exception e) { e.printStackTrace(); } } } 

This way you can get a screenshot of the full Phantomjs web page. When you use Phantomjs to get the full screenshot, you need to download Phantomjs first. Then run the Phantomjs script for a screenshot. You can refer to phantomjs.org for more on this.

+1
source

Here is my example of getting a fullscreen ScreenShot using C #, but just change:

  string _currentPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(One of your objects)).Location) + @"\Attachs\"; var filePath = _currentPath + sSName; if (!Directory.Exists(_currentPath)) Directory.CreateDirectory(_currentPath); Dictionary<string, Object> metrics = new Dictionary<string, Object>(); metrics["width"] = _driver.ExecuteScript("return Math.max(window.innerWidth,document.body.scrollWidth,document.documentElement.scrollWidth)"); metrics["height"] = _driver.ExecuteScript("return Math.max(window.innerHeight,document.body.scrollHeight,document.documentElement.scrollHeight)"); metrics["deviceScaleFactor"] = (double)_driver.ExecuteScript("return window.devicePixelRatio"); metrics["mobile"] = _driver.ExecuteScript("return typeof window.orientation !== 'undefined'"); _driver.ExecuteChromeCommand("Emulation.setDeviceMetricsOverride", metrics); _driver.GetScreenshot().SaveAsFile(filePath, ScreenshotImageFormat.Png); _driver.ExecuteChromeCommand("Emulation.clearDeviceMetricsOverride", new Dictionary<string, Object>()); _driver.Close(); 
0
source
 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("c:\\RESULT_FILENAME.png")); 

try it

-7
source

Source: https://habr.com/ru/post/1268047/


All Articles