Basic Playwright Questions with Answers
1. What is Playwright, and how does it compare to Selenium?
Playwright is an open-source automation framework developed by Microsoft for end-to-end testing of web applications.
?? Comparison with Selenium:
2. How do you install Playwright in a Node.js project?
Run the following command in your terminal:
npm init -y # Initialize a Node.js project (if not already done)
npm install playwright # Install Playwright
To install Playwright along with browsers, use:
npx playwright install
This installs Chromium, Firefox, and WebKit browsers.
3. What browsers does Playwright support?
Playwright supports: ? Chromium (Google Chrome & Microsoft Edge) ? Firefox ? WebKit (Safari) ? Microsoft Edge (via Chromium)
Unlike Selenium, Playwright provides built-in support for these browsers without external drivers.
4. How do you launch a browser in Playwright?
Here's how you can launch a browser:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch(); // Launch browser
const page = await browser.newPage(); // Open a new page
await page.goto('https://example.com'); // Navigate to a webpage
await browser.close(); // Close the browser
})();
To run the browser in headed mode (with UI), use:
const browser = await chromium.launch({ headless: false });
5. Explain the difference between page.goto() and page.waitForNavigation().
?? page.goto(url): Directly navigates to a URL and waits for the page to load.
await page.goto('https://example.com');
?? page.waitForNavigation(): Waits for a page navigation triggered by an action (like clicking a link).
await Promise.all([
page.waitForNavigation(),
page.click('a#nextPage') // Clicks a link that triggers navigation
]);
? Use page.goto() for direct navigation. ? Use page.waitForNavigation() when waiting for a page to change dynamically.
6. How do you handle different browser contexts in Playwright?
Browser contexts allow running multiple independent sessions in a single browser instance.
const browser = await chromium.launch();
const context1 = await browser.newContext();
const context2 = await browser.newContext(); // Independent session
const page1 = await context1.newPage();
const page2 = await context2.newPage();
await browser.close();
Each context has separate cookies, local storage, and session data.
7. What is the purpose of headless mode in Playwright?
Headless mode runs tests without opening a browser UI, making execution faster and more efficient.
const browser = await chromium.launch({ headless: true });
? Benefits: