How to handle authentication in Playwright?

Handling authentication in Playwright can be achieved in several ways depending on the kind of authentication a website uses. Here are a few ways to handle authentication in Playwright:

1. Using Cookies:

If you're dealing with a website that uses cookies for authentication, you can manually set these cookies in Playwright. Here is an example in JavaScript:

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

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await context.addCookies([
    { url: 'https://yourwebsite.com', name: 'cookieName', value: 'cookieValue' }
  ]);
  await page.goto('https://yourwebsite.com');
  await browser.close();
})();

2. Using HTTP Headers:

If the website uses HTTP headers for authentication, you can also set these headers in Playwright. Here is an example in Python:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context(extra_http_headers={
            'Authorization': 'Bearer your_token_here'
        })
        page = await context.new_page()
        await page.goto('https://yourwebsite.com')
        await browser.close()

asyncio.run(main())

3. Using Browser Contexts:

If the website uses a more complex form of authentication, like a login form, you can use Playwright's ability to manage browser contexts. Here is an example in JavaScript:

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

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://yourwebsite.com/login');
  await page.fill('#username', 'yourUsername');
  await page.fill('#password', 'yourPassword');
  await Promise.all([
    page.waitForNavigation(),
    page.click('#submit')
  ]);
  // Now you are logged in and can perform authenticated requests.
  await browser.close();
})();

Remember to replace 'https://yourwebsite.com', 'cookieName', 'cookieValue', 'your_token_here', 'yourUsername', and 'yourPassword' with your actual values.

Related Questions

Get Started Now

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