PhantomjsAPI之evaluate

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

from:http://phantomjs.org/api/webpage/method/evaluate.html

evaluate

evaluate(function, arg1, arg2, ...) {object}

Evaluates the given function in the context of the web page. The execution is sandboxed, the web page has no access to the phantom object and it can’t probe its own setting.

Examples

Get the page title from Bing.com (1)

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

page.open('http://m.bing.com', function(status) {

  var title = page.evaluate(function() {
    return document.title;
  });

  console.log(title);
  phantom.exit();

});

Get the page title from Bing.com (2)

As of PhantomJS 1.6, JSON-serializable arguments can be passed to the function. In the following example, the text value of a DOM element is extracted.

The following example achieves the same end goal as the previous example but the element is chosen based on a selector which is passed to the evaluate call:

page.open('http://m.bing.com', function(status) {

  var title = page.evaluate(function(s) {
    return document.querySelector(s).innerText;
  }, 'title');

  console.log(title);
  phantom.exit();

});

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

Any console message from a web page, including from the code inside evaluate, will not be displayed by default. To override this behavior, use the onConsoleMessage callback. The first example can be rewritten to:

Get the page title from Bing.com and print it inside evaluate

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

page.onConsoleMessage = function(msg) {
  console.log(msg);
}

page.open('http://m.bing.com', function(status) {

  page.evaluate(function() {
    console.log(document.title);
  });

  phantom.exit();

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值