How to emulate devices in Puppeteer?

Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. It's often used for web scraping, automated testing of web pages, and taking screenshots or generating PDFs of pages.

Emulating devices in Puppeteer is quite straightforward, as Puppeteer ships with device descriptors for a variety of devices which can be used directly.

Here are the steps to emulate a device in Puppeteer:

  1. First, you need to import the device descriptors. This can be done by requiring the DeviceDescriptors object from Puppeteer:

    const puppeteer = require('puppeteer');
    const devices = require('puppeteer/DeviceDescriptors');
    
  2. Next, you can select a specific device from the DeviceDescriptors object. For example, if you want to emulate an iPhone X, you would do:

    const iPhone = devices['iPhone X'];
    
  3. Then, you can use the page.emulate() function to tell Puppeteer to emulate this device:

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.emulate(iPhone);
    
  4. Lastly, you can navigate to your desired webpage and perform your usual Puppeteer tasks:

    await page.goto('https://example.com');
    // perform your actions here
    await browser.close();
    

Here is the whole code snippet:

const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iPhone = devices['iPhone X'];

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.emulate(iPhone);
  await page.goto('https://example.com');
  // perform your actions here
  await browser.close();
})();

This will make Puppeteer emulate an iPhone X when visiting "https://example.com".

Remember to replace 'iPhone X' with the device you want to emulate. You can find a list of all available devices here.

Related Questions

Get Started Now

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