Node js + PhantomJs:向page.evaluate发送数据

4
如何将变量从服务器发送到page.evaluate?
var test = 'Lorem Ipsum';

phantom = require('phantom')
    phantom.create(function(ph){
        ph.createPage(function(page) {
            page.open("http://www.google.com", function(status) {
            page.evaluate(function(){
               $('body').html(test);
            });
            page.render('google.pdf', function(){

             console.log('Page Rendered');
             ph.exit();
           });
        });
    });
});

感谢您提前的帮助。
编辑1:
现在它看起来像:
var message = function(){
    return {message: 'Hello Word'};
};

phantom = require('phantom')
    phantom.create(function(ph){
        ph.createPage(function(page) {
            page.open("http://www.google.com", function(status) {
            page.evaluate(function(content){
               $('body').html(content);
            }, message);
            page.render('google.pdf', function(){

             console.log('Page Rendered');
             ph.exit();
           });
       });
    });
});

现在我没有任何错误,但是我不知道如何处理这个对象以便在page.evaluate中使用它。

1个回答

1
尝试使用。
page.evaluate(function (...) {...}, function (err, data){...}, arg1, arg2, ...);

例子:
var message = 'hello world';
page.evaluate(function(content){
    $('body').html(content);
    return 'any data'
}, function (err, anydata) {}, message);

向页面添加jQuery。
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) {
    //jQuery Loaded.
    //Wait for a bit if site have AJAX
    setTimeout(function() {
        return page.evaluate(function() {
            // USE JQUERY HERE
            //
            //

            return
        }, function(err, result) {
            console.log(result);
            ph.exit();
        });
    }, 3000);
});

请查看自述文件:https://github.com/alexscheelmeyer/node-phantom


现在控制台里报错了:phantom stdout: TypeError: 'hello world' 不是一个函数 (在执行 'cb(page.evaluate.apply(page, [fn].concat(args)))' 时进行了评估) - form3
我尝试做类似这样的事情var message = function(){ return {message : 'hello world'}; };但现在我不知道如何处理这个对象以便在page.evaluate中使用它。 - form3
1
啊,抱歉,您正在使用Phantom for Node(一个连接到PhantomJS的桥梁)。evaluate将通过回调返回结果。 - damphat
谷歌不使用jQuery,因此在幻影页面中没有$。您可以尝试另一个页面或使用page.includeJs('http://path to a jquery cdn')。 - damphat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接