循环访问URL并在casperjs中为每个URL执行操作

时间:2016-05-16 01:19:03

标签: javascript phantomjs casperjs

我在Facebook上使用CasperJS进行了一些实验,我遇到了以下代码的问题:

casper.then(function(){
    stream = fs.open('usernames.csv', 'r');     //Open the list of usernames from file usernames.csv
    targetusername = stream.readLine();         //read the first line
    i = 0;                      //just a simple counter to loop through the list of usernames, nothing more

    while(targetusername) {                 //loop through the usernames line by line, where every username is on a line
        var url = "https://m.facebook.com/" + targetusername + "?v=timeline";       //append the username to the facebook url to get to the mobile web timeline of the target user
        console.log("current url is " + url);
        casper.thenOpen(url, function() {
            console.log ("I am here");
            fs.write(targetusername,this.getTitle() + "\n",'w');        //create a file with the username and insert the title of the facebook page as its first line
            fs.write(targetusername,this.page.plainText,'a');       //Dump the page textual content to file
        });

        targetusername = stream.readLine();
        i++;
    }

});

所以,基本上我有一个文件中的用户名列表,我打开每个用户的时间轴并转储文本,但是,casper.thenOpen部分:

casper.thenOpen(url, function() {
            console.log ("I am here");
            fs.write(targetusername,this.getTitle() + "\n",'w');        //create a file with the username and insert the title of the facebook page as its first line
            fs.write(targetusername,this.page.plainText,'a');       //Dump the page textual content to file
        });

不会在循环中执行。因此,它只执行一次,得到这个结果:

current url is https://m.facebook.com/ayman.vibo?v=timeline
current url is https://m.facebook.com/7ogzz?v=timeline
current url is https://m.facebook.com/elzokm88?v=timeline
I am here

而不是我想做的事情来得到这样的结果:

current url is https://m.facebook.com/ayman.vibo?v=timeline
I am here
current url is https://m.facebook.com/7ogzz?v=timeline
I am here
current url is https://m.facebook.com/elzokm88?v=timeline
I am here

我在这里做错了什么?

0 个答案:

没有答案