PhantomJS evaluate () 使用方法


发布日期 : 2022-07-08 10:54:12 UTC

访问量: 9 次浏览

PhantomJS evaluate()

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

语法

evaluate 语法如下所示 –

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

示例中带有控制台消息

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

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