CasperJS/PhantomJS .then in do/while Loop Doesn't Work

允我心安 提交于 2020-01-21 09:43:05

问题


Something like this seemed pretty logical to me but caused phantom to wtfcrash (That's what it's called in the log but doesn't give helpful info)...

do {
    casper.then(function() {
        var targetFound = false;
        links = this.evaluate(getLinks);

        var searchResultsAr = [];
        for (var link in links) {
            searchResultsAr.push(links[link].replace('/url?q=', '').split('&sa=U')[0]);
        }

        for (var result in searchResultsAr) {
            if (searchResultsAr[result] == target) {
                targetFound = true;
                casper.echo(targetFound);
                break;
            }
        }
        if(targetFound)
        {
            break;
        }
    });
}while(!targetFound);

回答1:


There are different possibilies, if you just want to repeat things static times you can use casper.repeat() -> how to have a variable value for casper.repeat

If you want to do a while with multipe then's inside and a break point you still have to use a recursive function as far as i know. Here is an example:

  ...
  casper.then(function() {
    loopValidConf.call(this, 0, 15);
  });
  casper.then(function() {
    casper.test.assert(exists, 'true after 15 tries!')
  });

  function loopValidConf(index, numTimes) {
    if (exists === true || index >= numTimes) {
      return;
    }
    casper.then(function() {
      casper.reload(function() {
        casper.echo("reset values");
      });
      casper.then(function() {
        // set some values here
      });
      casper.then(function() {
        casper.waitForSelector(".selector")
      });
      casper.then(function() {
        if (casper.exists('.targetSelector')) {
          exists = true;
          casper.echo('targetSelector exists!');
        } else {
          casper.echo('targetSelector doesnt exists, try it once more!');
        }
      });
    });
    casper.then(function() {
      loopValidConf.call(this, index + 1, numTimes);
    });
  }
  ...

This is still not the optimum (could cause memory problems), but it works. :)



来源:https://stackoverflow.com/questions/41964704/casperjs-phantomjs-then-in-do-while-loop-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!