我对 Nodejs 相当陌生,我正在使用 puppeteer 来自动化一些浏览,但我对某些场景的复杂性感到有点迷失。
我点击一个按钮,它会搜索一些记录(使用ajax)并将结果放在页面上。
等待响应/请求并不真正适合,因为我正在等待 2-3 个请求,具体取决于搜索类型 - 并且每个请求的响应 URL 完全相同。所以,我想我想等待这个特定 URL 的 3 个 url 响应完成。
也许我需要重新考虑一下,或者也许我已经很接近了?即使它似乎增加了responseCount, promise 总是超时
async function intercepted(resp) {
if (resp.url().includes('/ajaxpro/')) {
return 1
}
return 0
}
let responseCount = 0
page.on('response', async resp => {
responseCount += await intercepted(resp)
})
const getResponse = await new Promise((resolve, reject) => {
setTimeout(() => resolve(responseCount > 3), 60000)
})
最佳答案
尝试在收到每个响应后检查条件。
async function intercepted(resp) {
if (resp.url().includes('/ajaxpro/')) {
return 1
}
return 0
}
let responseCount = 0
page.on('response', async resp => {
let isTargetSearch = await intercepted(resp);
responseCount += isTargetSearch;
// - The current response is what we are looking for
// - and reached 3 times.
if(isTargetSearch && responseCount == 3) {
// Do what you need to do here
}
})
关于node.js - Puppeteer/Nodejs,如何等待事件条件满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733026/