How do I handle page authentication using username and password in Puppeteer?
Benjamin C
benjamin c profile pic

Handling page authentication using username and password in Puppeteer involves providing the credentials through the browser's authentication dialog or by directly filling the login form on the page. Here's a detailed explanation of how to handle page authentication in Puppeteer: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

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

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Handling page authentication using browser's authentication dialog: If the page requires basic HTTP authentication using the browser's built-in dialog, you can use thepage.authenticate() method to provide the username and password.

1
2
3
4
5
6
7
8
9

   const username = 'yourUsername';
   const password = 'yourPassword';

   await page.authenticate({ username, password });

   // Proceed with further actions on the authenticated page
   await page.goto('https://example.com');
   

In this example,page.authenticate() is used to provide the username and password for authentication. The{ username, password } object passed as an argument contains the credentials to be used. After authentication, you can proceed with further actions on the authenticated page, such as navigating to a specific URL. 3. Handling page authentication by filling the login form: If the page requires authentication through a login form, you can use Puppeteer's DOM manipulation methods to fill in the username and password fields and submit the form.

1
2
3
4
5
6
7
8
9
10
11
12
13

   const username = 'yourUsername';
   const password = 'yourPassword';

   await page.goto('https://example.com/login');

   await page.type('#usernameInput', username);
   await page.type('#passwordInput', password);
   await page.click('#loginButton');

   // Proceed with further actions on the authenticated page
   await page.goto('https://example.com');
   

In this example,page.type() is used to fill in the username and password fields with the provided values.page.click() is then used to simulate a click on the login button. After successful authentication, you can proceed with further actions on the authenticated page. By utilizing thepage.authenticate() method or filling in the login form using Puppeteer's DOM manipulation methods, you can handle page authentication using username and password in Puppeteer. This allows you to automate the process of authenticating with secure pages during web scraping, testing, or any other Puppeteer script that requires interacting with authenticated pages.