I'm trying to crawl a webpage using Nightmare, but want to wait for #someelem
to be present, only if it actually exists. Otherwise, I want Nightmare to move on. How can this be done using .wait()
?
I can't use .wait(ms)
. Using .wait(selector)
means Nightmare will keep waiting until the element is present, but if the page will never have this element, Nightmare will keep waiting forever.
The last option is to use .wait(fn)
. And I've tried something like this
.wait(function(cheerio) {
var $ = cheerio.load(document.body.outerHTML);
var attempt = 0;
function doEval() {
if ( $('#elem').length > 0 ) {
return true;
}
else {
attempt++;
if ( attempt < 10 ) {
setTimeout(doEval,2000); //This seems iffy.
}
else {
return true;
}
}
}
return doEval();
},cheerio)
So, wait and attempt again (upto a threshold), and if the element is not found, then just move on. The code seems wrong around setTimeout, because .wait
is done at the browser-scope.
Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…