Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在CasperJS中使用数组发布数据_Javascript_Web Scraping_Casperjs - Fatal编程技术网

Javascript 在CasperJS中使用数组发布数据

Javascript 在CasperJS中使用数组发布数据,javascript,web-scraping,casperjs,Javascript,Web Scraping,Casperjs,我正在使用CasperJS从example.com获取数据并将其发布到example.org casperjs代码: var data = []; casper.start('http://example.com', function() { this.echo('opened'); }); casper.then(function() { data.push( this.getHTML('div#a') ); // first text data.push( this.

我正在使用CasperJS从example.com获取数据并将其发布到example.org

casperjs代码:

var data = [];
casper.start('http://example.com', function() {
    this.echo('opened');
});
casper.then(function() {
    data.push( this.getHTML('div#a') ); // first text
    data.push( this.getHTML('div#b') ); // second text
    // ...
});
casper.thenOpen('http://example.org/', {
    method: 'post',
    data: {
        'data_one': data[0],
        'data_two': data[1],
        // ...
    }
});
casper.then(function() {
    this.echo( data );
});
控制台结果:

first text,second text,...
我希望在example.org上收到一些数据,但我添加的所有内容都是“data\u one”、“data\u two”。。。没有定义


如何正确发布数据?

问题是,在数据[0]和数据[1]可用之前,您访问了它们

CasperJS的执行是异步的。所有then*和wait*函数都是异步步进函数。调用它们只会向队列添加一个步骤,并且只有在调用casper.run时,才会执行队列

这意味着通过调用casper.thenOpen,您可以直接访问数据,但上一步尚未执行,因此尚未填充

例如,您可以将casper.thenOpen拆分为casper.then和casper.open:

请注意,还可以嵌套步骤。它们排队等待在当前步骤结束时执行:

casper.then(function() {
    data.push( this.getHTML('div#a') ); // first text
    data.push( this.getHTML('div#b') ); // second text

    ...

    this.thenOpen('http://example.org/', {
        method: 'post',
        data: {
            'data_one': data[0],
            'data_two': data[1],
            // ...
        }
    });
});
casper.then(function() {
    data.push( this.getHTML('div#a') ); // first text
    data.push( this.getHTML('div#b') ); // second text

    ...

    this.thenOpen('http://example.org/', {
        method: 'post',
        data: {
            'data_one': data[0],
            'data_two': data[1],
            // ...
        }
    });
});