如何使用Puppeteer从XHR请求获取body / json响应

时间:2019-06-20 15:33:54

标签: javascript node.js puppeteer

我想从正在使用Puppeteer抓取的网站上获取JSON数据,但我不知道如何取回请求的正文。这是我尝试过的:

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()); 
        } 
    }); 
})()

这仅返回一个promise未决函数。任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

response.json返回了一个承诺,我们需要等待它。

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