0

我有一个 casperjs 代码,如下所示:

var links = [
    { url : "http://engadget.com/" , name : "eng" },
    {url : "http://shoryuken.com/2013/02/01/help-save-super-arcade/",name: "shir"},
    {url: "http://theverge.com/",name:"thever" }
];

var eng_done = false , shir_done=false, thever_done=false;
var casper = require('casper');
for(i=0;i<links.length;i++){
    var url = links[i].url;
    var name = links[i].name;
    var instance_i = casper.create();
    instance_i.start(url,function(){
        console.log("Loading: "+ name);
        name_done = true;

    });
    instance_i.run(function(){

        exit(i);
    });

}


function exit(idz){

        console.log("Now exiting instance no => "+idz);
        if(eng_done & shir_done & thever_done){
            idz.exit();
        }

}

正如您可以清楚地看到我正在启动 3 个 casperjs 实例并立即退出它们,问题是它没有正确退出实例,因为 exit(i) 总是卡在 3 上。我不知道我在这里做错了什么...(请,网址只是示例)。

4

1 回答 1

0

所以我终于找到了我的问题的答案,把它贴在这里,这样有一天它可能会帮助别人:)我知道代码有点不标准,但它可以工作,所以我可以接受:)

var view_width = 1024, view_height = 768;
var clip_width = 1366, clip_height = 768;
var settings = {
pageSettings : {
    loadImages : true,
    loadPlugins : false
}   ,
 timeout : 120000,
 // // Set the viewport size
 viewportSize: {width: view_width, height: view_height},
 // // Set the position and the size of the clipped image
 clipRect: { 
  top: 0, 
  left: (view_width - clip_width)/2, 
  width: clip_width, 
  height: clip_height 
 },verbose: true, logLevel: 'debug'
};
var links = [
    { url : "http://google.com" , name : "google" },
    {url : "http://bing.com",name: "bing"},
    {url: "http://facebook.com/",name:"facebook" }
];
var casper = require('casper');

currentLink = 0;
for (var i=0, item; item=links[i]; i++) {
  // item is "some", then "example", then "array"
  // i is the index of item in the array
  var name = item.name;
 var instance_i = casper.create({logLevel : "debug",
 verbose : true});
 captureTheImage(instance_i,item.url,item.name,i);

}

function captureTheImage(i,u,n,e){
    var google_done=false,
    bing_done=false,
    facebook_done=false;
    i.start(u,function(){
    // item.name_done = true;
    this.capture("c:/name_"+e+"_"+n+".jpg",undefined,{
            format: 'jpg',
        quality: 75
        });
     n_done = true; 
    });
    i.clear();
    i.run(function(){

    console.log("Links done : "+currentLink);
    currentLink++;
    if(currentLink == 3){
        this.exit();
    }

    });     

}

希望它可以帮助某人:)

此外,如果您添加更多链接,您可以将其值传递给 captureTheImage,然后在它说 if(currentLink==) 的地方,使用 links.length 定义当前数组的长度,就像在 for 循环中一样。;)

最好的

于 2013-11-01T12:02:46.237 回答