How can I get automated screenshots of multiple sizes?

494    Asked by alexGONZALEZ in Cyber Security , Asked on Feb 15, 2022

 I am testing web apps for different screen sizes. Now I want to know if there is a method by which this process can be automated or I need to do this manually for every screen size? 

Answered by Alexander Coxon

There are multiple ways to get automated screenshots depending on whether you need a full page screenshot, whether the page requires some inputs to get the expected state and which device you are trying to simulate. For instance changing the size of the window is not enough to simulate a mobile device since you'll also have to consider the pixel ratio and in some cases the user agent. It can be as simple as launching the browser with a command line with Chrome:

chrome --headless --disable-gpu --screenshot --window-size=1280,1696 https://www.chromestatus.com/
or more advanced with a high-level API library like puppeteer which provides control over Chrome:
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iPhone = devices['iPhone 6'];
(async() => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.emulate(iPhone);
  await page.goto('https://www.google.com', {waitUntil: 'networkidle'});
  const screenshot = await page.screenshot({ fullPage: false });
  browser.close();
  fs.writeFileSync('./results/screenshot.png', screenshot);
})();
or more conventional with an automation library like Selenium available in multiple coding languages:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("mobileEmulation", {
    'deviceMetrics': { 'width': 360, 'height': 640, 'pixelRatio': 3.0 },
    'userAgent': "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"
})
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://stackoverflow.com/')
driver.get_screenshot_as_file('./results/screenshot.png')


Your Answer

Interviews

Parent Categories