PhantomJS - evaluate()



evaluate 方法将执行传递给它的函数。如果该函数包含控制台消息,它不会直接显示在终端中。要显示任何控制台消息,你需要使用 onConsoleMessage phantom 回调。

语法

语法如下:

wpage.evaluate(str)

示例

以下示例演示如何使用 evaluate() 方法。

var wpage = require('webpage').create(); 
wpage.open('http://localhost/tasks/test.html', function(status) { 
   var script1 = "function(){ var a = document.title; return a;}"; 
   var value = wpage.evaluate(script1); 
   console.log(value); 
   phantom.exit(); 
}); 

以上程序生成以下 输出

Welcome to phantomjs 

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

带有控制台消息的示例

我们考虑另一个带有控制台消息的示例。

var wpage = require('webpage').create(); 
wpage.onConsoleMessage = function(msg) { 
   console.log('CONSOLE: ' + msg); 
}; 

wpage.open('http://localhost/tasks/test.html', function(status) { 
   var script1 = "function(){ var a = document.title; console.log('hello world');return a;}"; 
   var value = wpage.evaluate(script1); 
   console.log(value); 
   phantom.exit(); 
});

以上程序生成以下输出。

CONSOLE: hello world 
Welcome to phantomjs
phantomjs_webpage_module_methods.htm
广告