无法评估PhantomJS中的jQuery函数 [英] Can not evaluate jquery function in phantomjs

查看:134
本文介绍了无法评估PhantomJS中的jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个嵌入jQuery并接受url和javascript代码的phantomjs代理服务.

I'd like to build a phantomjs broker service which embed with jquery and accept url and javascript code.

我写一个很好的例子:

var webPage = require('webpage');
var page = webPage.create();

page.onInitialized = function() {
    page.injectJs('js_lib/jquery.min.js');
    // page.includeJs('http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js');
    console.log('running document-start script.');
};

page.open("http://example.com", function(status) {
    if ( status === "success" ) {
        // var title = page.evaluateJavaScript('$(title).text()');
        var title = page.evaluate(function() {
            return $("title").text();
        });
        console.log(title);
    }
    phantom.exit();
});

要达到我的目的,需要使用page.evaluateJavaScript('$("title").text()'); 因为我想将{'url':somesite.com, 'js':'$("title").text()'}传递给该服务.

To achieve my purpose, need to use page.evaluateJavaScript('$("title").text()'); Because I'd like to pass {'url':somesite.com, 'js':'$("title").text()'} to this service.

然后我将代码切换到page.evaluateJavaScript:

page.open("http://example.com", function(status) {
    if ( status === "success" ) {
        var title = page.evaluateJavaScript('$("title").text()');
        console.log(title);
    }
    phantom.exit();
});

明白了:

$ phantomjs test.js
running document-start script.
ReferenceError: Can't find variable: title

  phantomjs://webpage.evaluate():1 in global code
  :0 in evaluateJavaScript
  test.js:20
  :285 in _onPageOpenFinished
null

推荐答案

我解决了!

不要写为page.evaluateJavaScript('$(title).text()');

需要使用function {}包装代码.

var webPage = require('webpage');
var page = webPage.create();

page.onInitialized = function() {
    page.injectJs('js_lib/jquery.min.js');
    // page.includeJs('http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js');
    console.log('running document-start script.');
};


page.open("http://example.com", function(status) {
    if ( status === "success" ) {
        var title = page.evaluateJavaScript('function() { return $("title").text();}');
        console.log(title);
    }
    phantom.exit();
});

这篇关于无法评估PhantomJS中的jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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