node.js - 如何在创建 page.click 事件后收集多个 Json 响应?

标签 node.js puppeteer

我有两页。在第一页上,我单击 '#btnSearch',第二页加载几个 JSON 文件作为响应。我需要将这些 JSON 文件的数据收集到数组 results 中。 我的问题是结果

            await page.goto(url, { waitUntil: 'load');
            await page.click('#btnSearch');

            const results = [];

            await page.on('response', async (response) => {
                if (response.url() && response.status() == 200) {
                    console.log('XHR response received');
                    results.push(await response.json());
                }
            });
            //await page.goto(url, {waitUntil : 'networkidle0'});
            await page.waitForSelector('#statusInfo');

            console.log(results);

最佳答案

page.on 事件监听器应在发出需要捕获的网络请求之前声明。

我不确定您的目标网站如何工作,因此我可能会做出错误的猜测,但如果我们尝试以这种方式更改代码会怎样:

const results = [];

// Open the first page
await page.goto(url, { waitUntil: 'load');

// Register an event listener
await page.on('response', async (response) => {
    if (response.url() && response.status() == 200) {
        console.log('XHR response received');
        results.push(await response.json());
    }
});

// Trigger navigation to the second page
await page.click('#btnSearch');

// wait until the navigation is finished
await page.waitForNavigation(); // <-- remove the line if script errors with timeout

await page.waitForSelector('#statusInfo');

console.log(results);

关于node.js - 如何在创建 page.click 事件后收集多个 Json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411119/

相关文章:

javascript - 是否可以在 Selenium 或 Puppeteer 等自动化软件中读取传入的 HTTP 请求?

javascript - 如何将变量传递给 Puppeteer page.on?

node.js - 前端发送正常的http请求有哪些方式?

javascript - 如何通过 node.js 将可下载的 pdf 发送到 javascript 客户端?

testing - 开 Jest 测试描述范围变量

javascript - 如何将 Puppeteer 与 Stripe 元素结合使用

node.js - 在nodejs上使用GSUTIL访问google play商店数据

javascript - 如何在 Node js 和 mongodb 中获取当前保存的文档 _id?

javascript - 在 Node 中抓取 .aspx 页面

node.js - 是否可以使用 puppeteer 将 Javascript 对象传递给 nodejs?