How can I set viewport in Puppeteer?

In Puppeteer, the setViewport() function is used to set the viewport. This function can be called on a page object and it takes an object as an argument. The object should include the width and height properties, defining the desired viewport size.

Here is an example of how to set the viewport using Puppeteer in a Node.js environment:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setViewport({width: 1280, height: 800});
  await page.goto('https://example.com');
  await page.screenshot({path: 'example.png'});

  await browser.close();
})();

In the above code:

  • We first require the puppeteer module.
  • We then launch a new browser instance using puppeteer.launch().
  • We open a new page in the browser using browser.newPage().
  • We set the viewport to a width of 1280 pixels and a height of 800 pixels using page.setViewport().
  • We navigate to a website using page.goto().
  • We take a screenshot of the page and save it as 'example.png' using page.screenshot().
  • Finally, we close the browser using browser.close().

Remember, Puppeteer operations are asynchronous, hence we use the async/await syntax to ensure that each operation completes before the next one begins.

Also note that you can set the device scale factor, whether the viewport is in landscape mode, and the screen orientation through the setViewport() method.

For example:

await page.setViewport({
  width: 1280,
  height: 800,
  deviceScaleFactor: 1,
  isMobile: false,
  hasTouch: false,
  isLandscape: false
});

In the above code, we set additional properties like deviceScaleFactor, isMobile, hasTouch, and isLandscape.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon