Playwright - Login examples
Here is a list of example scripts for login operation to various popular websites using Playwright framework. These script can be a good basis to help with automating login page for your application.
Login to Microsoft Live account
The following example scripts shows interaction with Live login page to perform the login operation.
const { chromium } = require('playwright');
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
try{
await page.goto('https://login.live.com/');
await page.setViewportSize({ width: 1928, height: 1270 });
await page.locator("[name=\"loginfmt\"]").click();
await page.locator("[name=\"loginfmt\"]").fill("[email protected]");
await Promise.all([
page.waitForNavigation(),
page.locator('text=Next').click()
]);
await page.locator("[name=\"passwd\"]").click();
await page.locator("[name=\"passwd\"]").fill("newpassword");
await Promise.all([
page.waitForNavigation(),
page.locator("[id=\"idSIButton9\"]").click()
]);
} catch(e) {
//auto-screenshot on failure
await page.screenshot({ path: 'failed.png', fullPage: true });
throw e;
} finally {
await context.close()
await browser.close();
}
Login to HackerNews
The following example demonstrates automating login operation to HackerNews. The script interacts with elements on the page based on their position in the DOM.
const { chromium } = require('playwright');
const browser = await chromium.launch({headless:false});
const context = await browser.newContext();
const page = await context.newPage();
try{
await page.goto('https://news.ycombinator.com/login', { waitUntil:'networkidle' });
await page.setViewportSize({ width: 1928, height: 850 });
await page.locator("table:nth-child(1) tr:nth-of-type(1) input").click();
await page.locator("table:nth-child(1) tr:nth-of-type(1) input").fill("throwaway6202");
await page.locator("table:nth-child(1) tr:nth-of-type(1) input").press("Tab");
await page.locator("table:nth-child(1) tr:nth-of-type(2) input").fill("testtest");
await Promise.all([
page.waitForNavigation(),
page.click('input[value=login]')
]);
} catch(e) {
//auto-screenshot on failure
await page.screenshot({ path: 'failed.png', fullPage: true });
throw e;
} finally {
await context.close()
await browser.close();
}
In this article