问题
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