How do I use Playwright to emulate different devices?

Playwright is a Node.js library that allows you to automate and test modern browsers including Chrome, Firefox, and Safari. One of its features is the ability to emulate different devices. Here's how you can use it:

Python Example

Firstly, you need to install the playwright library. You can do this using pip:

pip install playwright

Next, you need to download the browsers that you will interact with:

playwright install

Here is a Python example where we use the playwright to emulate an iPhone 11:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    iPhone_11 = p.devices["iPhone 11"]
    browser = p.webkit.launch()
    context = browser.new_context(
        **iPhone_11,
        locale="en-US",
        geolocation={"longitude": 12.492507, "latitude": 41.889938},
        permissions=["geolocation"]
    )
    page = context.new_page()
    page.goto("https://maps.google.com")
    page.click(".widget-mylocation-button-icon")
    page.screenshot(path="example.png")
    browser.close()

In this example, we use the predefined device descriptor for iPhone 11, "iPhone 11". You can replace it with any other device from the list of device descriptors.

JavaScript Example

Firstly, install the playwright library using npm:

npm i playwright

Here is a JavaScript example where we use the playwright to emulate an iPhone 11:

const playwright = require('playwright');

(async () => {
  const iPhone11 = playwright.devices['iPhone 11'];
  const browser = await playwright.webkit.launch();
  const context = await browser.newContext({
    ...iPhone11,
    locale: 'en-US',
    geolocation: { longitude: 12.492507, latitude: 41.889938 },
    permissions: ['geolocation'],
  });
  const page = await context.newPage();
  await page.goto('https://maps.google.com');
  await page.click('.widget-mylocation-button-icon');
  await page.screenshot({ path: 'example.png' });
  await browser.close();
})();

In both examples, we are emulating an iPhone 11 device and visiting Google Maps, setting our location to Rome, Italy, and taking a screenshot.

Remember that you can use any of the devices listed in the Playwright's DeviceDescriptors.

Related Questions

Get Started Now

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