This question already has answers here:
Passing variable into page.evaluate - PhantomJS

(3个答案)


3年前关闭。




好的,这是我的casperjs函数:
if(casper.exists(ac2)){

    var accountnumber = this.fetchText('div.arabic:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > a:nth-child(1)');
    var redir = accountnumber.substr(1);

casper.then(function() {

var uel = "https://example.ws/send.html?f=" + redir;
this.thenOpen(uel, function() {
casper.wait(10000, function() {
    casper.then(function() {
    var accountnumber1 = this.fetchText('div.arabic:nth-child(1) > font:nth-child(1)');
    var acccc = accountnumber1.split(' ');
    system.stdout.writeLine(acccc[3]); // this output a number
    var amount = acccc[3];
var result = amount * 0.019;
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
    system.stdout.writeLine(needed); // this output a number
    this.evaluate(function() {

    document.getElementById('account').value = '6028';
    document.getElementsByName('data')[0].value = needed; // this just does not work even though i know there a number needed in var needed

    });
    //this.click("input#sbt.button[type='submit']");

casper.wait(10000, function() {
    casper.then(function() {
    this.capture("capture1.jpg");
    var el2 = this.getHTML();
    fs.write('result.html', el2, 'w');
    });
   });
  });});
 });
});

} else {

this.exit();

}

由于某种原因,我只是无法获取变量以正确发送到此函数:
    this.evaluate(function() {

    document.getElementById('account').value = '6028';
    document.getElementsByName('data')[0].value = needed; // this just does not work even though i know there a number needed in var needed

    });

谁能帮我解决这个问题,以便正确地通过数字评估功能。

最佳答案

needed变量作为从PhantomJS的 evaluate() 派生的 evaluate() 函数的参数传递。

您混合使用两种不同的上下文。在页面DOM环境中(在evaluate()内部),needed是未知的,因为evaluate()是沙盒化的。

我设置了var neededCasperContext = needed;以向您显示差异,但是您当然可以直接传递它。

var neededCasperContext = needed;

this.evaluate(function(neededPageDomContext) {

    document.getElementById('account').value = '6028';
    document.getElementsByName('data')[0].value = neededPageDomContext;
}, neededCasperContext);

关于javascript - CasperJS传递变量进行评估无法使其正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22597987/

10-12 15:39