制作page.click事件后如何收集多个Json响应? [英] How to collect several Json responses after I made page.click event?
本文介绍了制作page.click事件后如何收集多个Json响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两页.在第一页我点击 '#btnSearch'
并且第二页加载几个 JSON 文件作为响应.我需要将这些 JSON 文件的数据收集到数组 results
中.我的问题是 results
是 empty.
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);
推荐答案
page.on
事件侦听器应该在您需要捕获的网络请求发出之前声明.
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);
这篇关于制作page.click事件后如何收集多个Json响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文