How can I perform multi-tab testing using Playwright?

Playwright is a powerful tool for automating web browser interactions and it supports multi-tab testing as well. Here is how you can do it.

In Playwright, you can open a new tab using the newPage function and then perform actions on that new page. You can switch between tabs using their respective page objects.

Here is an example of how to perform multi-tab testing using Playwright in JavaScript:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();

  // Open new tab
  const page1 = await context.newPage();

  // Perform actions on the first tab
  await page1.goto('https://example.com');

  // Open another tab
  const page2 = await context.newPage();

  // Perform actions on the second tab
  await page2.goto('https://google.com');

  // You can switch back to the first tab and do something
  await page1.click('text="Some text on page 1"');

  // And switch back to the second tab again
  await page2.click('text="Some text on page 2"');

  // Close the browser
  await browser.close();
})();

In Python, the idea is the same, but the syntax is slightly different:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()

    # Open new tab
    page1 = context.new_page()

    # Perform actions on the first tab
    page1.goto('https://example.com')

    # Open another tab
    page2 = context.new_page()

    # Perform actions on the second tab
    page2.goto('https://google.com')

    # You can switch back to the first tab and do something
    page1.click('text="Some text on page 1"')

    # And switch back to the second tab again
    page2.click('text="Some text on page 2"')

    # Close the browser
    browser.close()

Remember to handle the pages with care, as any unhandled promise rejection or error can lead to a crash of your program. Always handle errors and make sure to close the pages when you're done with them.

Related Questions

Get Started Now

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