如何在后续调用中重用casperJS调用中填充的变量? [英] How can I reuse a variable populated within a casperJS call in a subsequent call?

查看:54
本文介绍了如何在后续调用中重用casperJS调用中填充的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在CasperJS脚本中遇到以下范围问题。传递给casper.thenOpenAndEvaluate()时,baseTargetUrl是未定义的。为什么会这样,我该如何解决?

I have the following scoping problem in a CasperJS script. baseTargetUrl is undefined when passing into casper.thenOpenAndEvaluate(). Why is this and how can I work around it?

var baseTargetUrl;
        .....
casper.then(function() {
    baseTargetUrl = this.evaluate(function() {
        return __utils__.getElementByXPath('//*[@id="wrapper"]/div[1]/a[2]')["href"];
    });
    console.log('logging: '+baseTargetUrl); // works
});

casper.thenOpenAndEvaluate(baseTargetUrl ,function() { //baseTargetUrl is undefined here
    var test = document.querySelector('myselector');
    //do other stuff

});


推荐答案

如您所知,我们无法从外部获取变量异步调用。

As you know we can't grab variable from outside async calls. This seem kinda hacky but this is the best I've got for now ....

var baseTargetUrl;
        .....
casper.then(function() {
    baseTargetUrl = this.evaluate(function() {
        return __utils__.getElementByXPath('//*[@id="wrapper"]/div[1]/a[2]')["href"];
    });
    console.log('logging: '+baseTargetUrl); // works

    this.thenOpenAndEvaluate(baseTargetUrl ,function() { // 'this' being the instance of casper
        var test = document.querySelector('myselector');
        //do other stuff

    });
});

这篇关于如何在后续调用中重用casperJS调用中填充的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆