How to collect several Json responses after I made page.click event?

喜夏-厌秋 提交于 2019-12-11 04:29:57

问题


I have two pages. On First page I make the click '#btnSearch'and the Second pages loads several JSON files as response. I need to collect the data of those JSON files into array results. My problem is that results are empty.

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

回答1:


page.on event listener should be declared before the network requests that you need to catch are made.

I'm not sure how your target site works so I may make a wrong guess, but what if we try to change code in this way:

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


来源:https://stackoverflow.com/questions/58411119/how-to-collect-several-json-responses-after-i-made-page-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!