How can I set up Playwright for multiple browsers?

Playwright is a Node.js library used for automating browser tasks. It supports various web browsers like Chromium, Firefox, and WebKit. Here's how you can set up Playwright for multiple browsers.

First, you need to install Playwright. You can do this via npm (Node Package Manager):

npm install playwright

This command installs Playwright and browser binaries for Chromium, Firefox, and WebKit. Once you've installed Playwright, you can then launch these browsers.

In JavaScript:

You can create an instance of a browser, open a new page, navigate to a URL and close the browser. Here is an example with Chromium, Firefox, and WebKit:

const playwright = require('playwright');

(async () => {
  for (const browserType of ['chromium', 'firefox', 'webkit']) {
    const browser = await playwright[browserType].launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto('http://whatsmyuseragent.org/');
    await page.screenshot({ path: `example-${browserType}.png` });
    await browser.close();
  }
})();

In the above code, we loop over the three browser types supported by Playwright (chromium, firefox, webkit). For each browser type, we launch the browser, create a new browser context, open a new page, navigate to 'http://whatsmyuseragent.org/', take a screenshot and store it with a name that includes the browser type, and finally close the browser.

In Python:

Playwright also provides a Python version. You can install it using pip:

pip install playwright

And you need to run playwright install to download the necessary browser binaries:

playwright install

Here is an example similar to the JavaScript version but in Python:

from playwright.sync_api import Playwright, sync_playwright

def run(playwright: Playwright) -> None:
    for browser_type in [playwright.chromium, playwright.firefox, playwright.webkit]:
        browser = browser_type.launch()
        context = browser.new_context()
        page = context.new_page()
        page.goto('http://whatsmyuseragent.org/')
        page.screenshot(path=f'example-{browser_type.name}.png')
        browser.close()

with sync_playwright() as playwright:
    run(playwright)

In the Python example, we again loop over the three browser types. For each browser type, we launch the browser, create a new context, open a new page, navigate to 'http://whatsmyuseragent.org/', take a screenshot and store it with a name that includes the browser type's name, and finally close the browser.

Related Questions

Get Started Now

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