javascript - 如何检索CasperJS打开的最后一个页面的内容?

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

最佳答案

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/

相关文章:

javascript - 等待 Casper.js 中的 URL 更改?

javascript - 试图在事件处理程序上实现闭包?错误 : undefined

javascript - 如何使用 CasperJS 获取下拉框的值

javascript - PHP 和 Javascript toast

随机十进制值后的 Javascript 舍入值

javascript - 如何测试一个div是否不显示?

javascript - CasperJS - 继续步骤超时

javascript - 循环后数组的值丢失

javascript - react 组件上的功能没有及时设置

javascript - jQuery:拖动/调整圆形 div 中的图像位置