对 this.getPageContent()
的调用不会检索最后打开的页面的内容。
如何检索最后打开的页面的内容?
var casper = require("casper").create({
verbose: true,
logLevel: "debug",
waitTimeout: 10000,
retryTimeout: 1000
});
casper.start(function() {
this.open('http://example.com/contentTypes', {
method: 'get',
headers: {'Accept': 'application/json'}
});
console.log(this.getCurrentUrl());
});
casper.then(function() {
// get content of http://example.com/contentTypes << OK
var ressources_type = JSON.parse(this.getPageContent());
require('utils').dump(ressources_type);
for (var i in ressources_type.data) {
this.thenOpen('http://example.com/ressource?type=' + ressources_type['data'][i]['key'] , {
method: 'get',
headers: { 'Accept': 'application/json'}
});
// get content of http://example.com/contentTypes instead of http://example.com/ressource?type=' + ressources_type['data'][i]['key']
var ressources = JSON.parse(this.getPageContent());
require('utils').dump(ressources);
for (var j in ressources['data']) {
...
}
}
});
casper.run(function() {
this.echo('Done.').exit();
});
最佳答案
CasperJS 本质上是异步的。每个 then*
和 wait*
调用(步骤函数)都会调度传递的函数,但不会立即执行它。您将异步调用 (thenOpen
) 与同步调用 (getPageContent
) 混合在一起。
您需要将每个同步调用移至步骤函数中。
this.thenOpen('http://example.com/ressource?type=' + ressources_type['data'][i]['key'] , {
method: 'get',
headers: { 'Accept': 'application/json'}
});
this.then(function(){
var ressources = JSON.parse(this.getPageContent());
require('utils').dump(ressources);
for (var j in ressources['data']) {
...
}
});
关于javascript - 如何检索CasperJS打开的最后一个页面的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25424854/