Javascript 如何使casperjs重复循环,直到满足特定条件?
我试图让casperjs处理以下情况: 一个web页面加载,然后在该页面中加载数据项 还有一个“读取更多”按钮,该按钮依次加载更多数据 项目 我需要脚本递归地检查“阅读更多”按钮是否存在(因为有许多数据项要加载),如果存在,请单击它,否则继续脚本的其余部分并将整个页面作为jpeg输出 我试着写下面的代码,但它没有像我希望的那样循环。它只需单击一次按钮,然后输出图像,即使加载了更多数据,按钮仍然存在,以便再次单击Javascript 如何使casperjs重复循环,直到满足特定条件?,javascript,phantomjs,casperjs,Javascript,Phantomjs,Casperjs,我试图让casperjs处理以下情况: 一个web页面加载,然后在该页面中加载数据项 还有一个“读取更多”按钮,该按钮依次加载更多数据 项目 我需要脚本递归地检查“阅读更多”按钮是否存在(因为有许多数据项要加载),如果存在,请单击它,否则继续脚本的其余部分并将整个页面作为jpeg输出 我试着写下面的代码,但它没有像我希望的那样循环。它只需单击一次按钮,然后输出图像,即使加载了更多数据,按钮仍然存在,以便再次单击 var casper = require('casper').create({
var casper = require('casper').create({
verbose : true,
logLevel : 'debug',
pageSettings : {
"userAgent" : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10',
"loadImages" : false,
"webSecurityEnabled" : false,
"ignoreSslErrors" : true
},
});
var urls = {
login : 'http://www.website.com/login',
details : 'http://www.website.com/details',
};
casper.start(urls.login, function() {
//login stuff
});
//the function I'm trying to recursively loop before moving on to saving the capture image
function checkMore() {
//check to see if the 'read more' button exists
if (casper.exists('a.read-more')) {
//click the button to load more items
casper.click('a.read-more');
//wait for the items to load, then run the check again
casper.wait(3000, function() {
casper.run(checkMore);
});
}
}
casper.thenOpen(urls.details, function() {
//wait for the page along with ajax items to load shortly after
this.wait(3000, function() {
this.run(checkMore);
});
});
casper.then(function() {
//output the result
this.capture('output.jpg');
});
casper.run();
Pius有正确的想法,我修改了我的代码,解决方案如下
var urls = {
login : 'http://www.website.com/login',
details : 'http://www.website.com/details',
};
casper.start(urls.login, function() {
//login stuff
});
//the function I'm trying to recursively loop before moving on to saving the capture image
function checkMore() {
//check to see if the 'read more' button exists
if (casper.exists('a.read-more')) {
//click the button to load more items
casper.click('a.read-more');
//wait for the items to load, then run the check again
casper.wait(3000, checkMore);
}
}
casper.thenOpen(urls.details, function() {
//wait for the page along with ajax items to load shortly after
this.wait(3000, checkMore);
});
casper.then(function() {
//output the result
this.capture('output.jpg');
});
casper.run();
我认为你应该只调用
run
一次。您可以直接将checkMore
传递给wait函数,即this.wait(3000,checkMore)
。但是,在checkMore
中,此
引用不起作用-因此您必须编写例如casper.exists(“…”)
。您是否考虑过等待waitForSelector
按钮?这似乎很适合这种情况。它是如何循环的?您还没有描述问题所在。@pius您的两个评论一起给出答案。那就继续吧。:)如果a.readmore
永远不可见会发生什么?你不应该考虑这个吗?Rippo,这就是为什么我检查“如果(CASPER)存在(A.Read -For)”。如果该链接不存在,或者该链接已停止显示,则脚本将不会单击,也不会再次调用checkMore函数。如果ajax调用失败,我最初的问题主要是如何使循环工作,直到满足某个条件,在我的情况下,就是要显示一个按钮。而不是如何防弹对抗ajax失败,因为在我的案例中,这并不是真正的问题!很高兴它不适用于你的情况。