如何检索CasperJS打开的最后一页的内容?

时间:2014-08-21 11:11:03

标签: javascript casperjs

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();
});

1 个答案:

答案 0 :(得分:1)

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']) {
        ...
    }
});