puppeteer:在 DevTools 的网络选项卡中访问特定请求的 JSON 响应

puppeteer: Access JSON response of a specific request as in the network tab of DevTools

我想直接获取截图中最后一个HTTP请求的响应。

当前的 puppeteer 代码如下所示。谁能告诉我如何修改它以便它直接从浏览器获得 JSON 响应?谢谢

const puppeteer = require('puppeteer');

(async () => {
    //  const browser = await puppeteer.launch();
    const browser = await puppeteer.launch({
        headless: false
        , args: ['--user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3312.0 Safari/537.36"']
    });
    const page = await browser.newPage();
    await page.goto('https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2');
    await page.goto('https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2');

    const linkHandlers = await page.$x("//div[@id='enhancers']//a[@data-track-event='Table See-All']");
    if (linkHandlers.length > 0) {
        await linkHandlers[0].click();
    } else {
        throw new Error("Link not found");
    }

    const html = await page.content()
    //await browser.close();
    console.log(html)
})();

您可以使用 page.waitForResponse to wait for the response and response.json 将响应解析为 JSON。

代码

await linkHandlers[0].click(); 部分替换为:

const [response] = await Promise.all([
    page.waitForResponse(response => response.url().includes('/gene/api/data/Enhancers')),
    linkHandlers[0].click()
]);
const dataObj = await response.json();
console.log(dataObj);

这将首先等待响应(同时进行点击)。在检测到响应后,响应被解析为 JSON。要以纯文本形式获取响应结果(而不是解析它),您可以使用 response.text()