简体   繁体   English

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

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

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.我想从我用 Puppeteer 抓取的网站获取 JSON 数据,但我不知道如何取回请求的正文。 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.任何帮助都会很棒。

As response.json returns a promise we need to await it.response.json返回一个 promise 时,我们需要等待它。

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

Could you help me with advice. 你能帮我提建议吗? How to extract all json responses to array and out of this function? 如何提取所有对数组的json响应并从此函数中提取出来?

await page.on('response', async (response) => {    
    if (response.url()){
        console.log('XHR response received'); 

        let rest = await response.json();
    } 
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM