我有两页。在第一页上,我单击 '#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/