最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

我做了page.click事件后如何收集几个Json响应?

运维笔记admin83浏览0评论

我做了page.click事件后如何收集几个Json响应?

我做了page.click事件后如何收集几个Json响应?

我有两页。在第一页上,单击'#btnSearch',然后在第二页上加载几个JSON文件作为响应。我需要将这些JSON文件的数据收集到数组results中。我的问题是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);
发布评论

评论列表(0)

  1. 暂无评论