【问题标题】:How to collect several Json responses after I made page.click event?制作 page.click 事件后如何收集多个 Json 响应?
【发布时间】:2019-10-16 20:25:40
【问题描述】:

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

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

【问题讨论】:

  • 我认为您在开始获得结果之前已经进入了 console.log。

标签: node.js puppeteer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2013-04-30
    • 1970-01-01
    • 2011-07-26
    • 2020-08-20
    • 2012-02-13
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多