【问题标题】:How to get body / json response from XHR request with Puppeteer如何使用 Puppeteer 从 XHR 请求中获取 body / json 响应
【发布时间】:2019-11-03 11:27:30
【问题描述】:

我想从一个使用 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 挂起函数。任何帮助都会很棒。

【问题讨论】:

标签: javascript node.js puppeteer webautomation


【解决方案1】:

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

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

【讨论】:

  • await page.on 不是必需的——page.on 返回一个页面对象,用于链接更多 .on 调用,而不是承诺。对于那些孤立地看到这个线程的人,还有page.waitForResponse 可以让您直接在异步链中检索响应主体。
  • 好收获@ggorlen!
猜你喜欢
  • 2018-11-15
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多