用于while循环的casperjs脚本中的异步进程

用于while循环的casperjs脚本中的异步进程

本文介绍了用于while循环的casperjs脚本中的异步进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用while循环来打开csv文件中的用户名列表。对于这些用户名的每个用户名,我必须打开一个URL并将页面转储到文件中。

I'm using a while loop to open a list of usernames from a csv file. For each username of these, I have to open a URL and dump the page into a file.

但是,然后casper.thenOpen始终只运行一次。我从了解到这是由于它是一个异步过程。我需要对下面的代码执行相同的操作:

However, then casper.thenOpen always runs only one time. I understood from Asynchronous Process inside a javascript for loop that this is due to that it is an asynchronous process. I need to do the same for my code below:

casper.then(function(){
    stream = fs.open('usernames.csv', 'r');
    targetusername = stream.readLine();
    i = 0;

    while(targetusername) {
        var url = "http://blablalb" + targetusername;
        console.log("current url is " + url);

        casper.thenOpen(url, function() {
            console.log ("I am here");
            fs.write(targetusername,this.getTitle() + "\n",'w');
            fs.write(targetusername,this.page.plainText,'a');
        });

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

});

casper.thenOpen始终只运行一次,因此输出如下:

The casper.thenOpen always runs only one time, giving me this output:

current url is first_url
current url is second_url
current url is third_url
I am here

我需要的是这样

current url is first_url
I am here
current url is second_url
I am here
current url is third_url
I am here

我正在拔头发以使循环正常运行!

I'm pulling my hair out to get that while loop running correctly!

推荐答案

我可以达到所需的准确输出:

I could reach the exact output that I needed:

current url is first_url
I am here
current url is second_url
I am here
current url is third_url
I am here

使用重复功能,如下所示:

using the repeat function, as follows:

casper.then(function(){
    stream = fs.open('usernames.csv', 'r');

    casper.repeat(3, function() {

        targetusername = stream.readLine();
        var url = "http://blablalb" + targetusername;
        console.log("current url is " + url);

        casper.thenOpen(url, function() {
            console.log ("I am here");
            fs.write(targetusername,this.getTitle() + "\n",'w');
            fs.write(targetusername,this.page.plainText,'a');
        });

    }

)});

这篇关于用于while循环的casperjs脚本中的异步进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:32