How to get body / json response from XHR request with Puppeteer

Rusty picture Rusty · Jun 20, 2019 · Viewed 9k times · Source

I want to get the JSON data from a website I'm scraping with Puppeteer, but I can't figure how to get the body of the request back. Here's what I've tried:

const puppeteer = require('puppeteer')
const results = [];
(async () => {
    const browser = await puppeteer.launch({
        headless: false
    })
    const page = await browser.newPage()
    await page.goto("https://capuk.org/i-want-help/courses/cap-money-course/introduction", {
        waitUntil: 'networkidle2'
    });

    await page.type('#search-form > input[type="text"]', 'bd14ew')  
    await page.click('#search-form > input[type="submit"]')

    await page.on('response', response => {    
        if (response.url() == "https://capuk.org/ajax_search/capmoneycourses"){
            console.log('XHR response received'); 
            console.log(response.json()); 
        } 
    }); 
})()

This just returns a promise pending function. Any help would be great.

Answer

hardkoded picture hardkoded · Jun 20, 2019

As response.json returns a promise we need to await it.

page.on('response', async (response) => {    
    if (response.url() == "https://capuk.org/ajax_search/capmoneycourses"){
        console.log('XHR response received'); 
        console.log(await response.json()); 
    } 
});