CasperJS 很棒,但它没有将我的控制台输出发布到我的本地主机。
casper.wait(5000, function () {
casper.wait(1000, function () {
casper.then(function(){
for (var i = 0 ; i < 10; i++) {
var description = casper.fetchText(x('//*[@id="acDataId-local'+i+'"]/a')); //*[@id="acDataId-local0"]/a
console.log(description);
var target_date = casper.fetchText(x('//*[@id="dtDataId-local'+i+'"]/text()[1]'));
console.log(target_date);
var target_location = casper.fetchText(x('//*[@id="veDataId-local'+i+'"]'));
console.log(target_location);
console.log(i, description)
casper.then(function () {
casper.open('http://localhost:1337/events', {
method: 'post',
data: {
'description': description,
'target_date': target_date,
'target_location': target_location,
},
headers: {
"stuff":"stuff"
}
});
});
}
this.echo('POST ' + i );
});
});
});
casper.run();
Console.log 正是在我想要的时候输出,但它只发布最后一项。我尝试在多个地方添加 casper.wait 但似乎没有帮助!
最佳答案
CasperJS 中的所有 then*
和 wait*
函数均为 asynchronous step functions和 JavaScript has function-level scope .
这意味着 for 循环会立即执行,并计划在 for 循环完全完成后执行几个 then()
步骤。此时,函数级变量 description
、target_date
等都将具有最后一个 i
和 i< 的值
将为 10。这是一个通用的 JavaScript 示例:JavaScript closure inside loops – simple practical example
您可以
将两个调用
casper.then()
和casper.open()
更改为单个调用casper.thenOpen()
> 其中循环变量直接传递给函数:casper.thenOpen('http://localhost:1337/events', { method: 'post', data: { 'description': description, 'target_date': target_date, 'target_location': target_location, }, headers: { "stuff":"stuff" } });
或者通过引入 IIFE 来“关闭”每次迭代的变量:
for (var i = 0 ; i < 10; i++) { (function(){ var description = casper.fetchText(x('//*[@id="acDataId-local'+i+'"]/a')); //*[@id="acDataId-local0"]/a console.log(description); var target_date = casper.fetchText(x('//*[@id="dtDataId-local'+i+'"]/text()[1]')); console.log(target_date); var target_location = casper.fetchText(x('//*[@id="veDataId-local'+i+'"]')); console.log(target_location); console.log(i, description) casper.then(function () { casper.open('http://localhost:1337/events', { method: 'post', data: { 'description': description, 'target_date': target_date, 'target_location': target_location, }, headers: { "stuff":"stuff" } }); }); })(); }
关于javascript - CasperJS 仅从我的 for 循环中多次发布最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568147/