What is the Puppeteer API method to retrieve the response headers of a network request?
Ava W
ava w profile pic

The Puppeteer API method to retrieve the response headers of a network request isresponse.headers(). Here's a detailed explanation: 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. Retrieving the response headers usingresponse.headers(): To retrieve the response headers of a network request, you can use theresponse.headers() method.

1
2
3
4
5
6
7
8
9

   page.on('response', async (response) => {
     const headers = response.headers();

     console.log('Response headers:', headers);
   });

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

In this example, an event listener is set up usingpage.on('response') to capture network responses. When a response is received, theresponse.headers() method is called to retrieve the response headers. The headers are then logged to the console. By utilizingresponse.headers(), you can access the response headers of a network request in Puppeteer. This is useful for extracting information from the headers, such as content type, cache control directives, cookies, and more. You can analyze and process the response headers as needed for various web scraping, testing, or automation tasks.