Phantom.js:在本地使用,已安装 npm,jquery

Phantom.js: Use locally, npm installed, jquery

他们建议在许多链接上加载 jquery 以便在页面 dom 中进行抓取。遵循的常见模式是:

var page = require('webpage').create();
var url = 'http://example.com';

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

page.open(url, function (status) {
  if(status==='success') {
    page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
        //Do stuff there
        phantom.exit();
    });
  } else {
    phantom.exit(1);
  }
});

但有时通过 npm 在本地安装 jquery 对网络来说是理智的:

npm install jquery

但是如何包含本地安装的jquery?

请参阅page.injectJs方法:http://phantomjs.org/api/webpage/method/inject-js.html

page.open('http://www.phantomjs.org', function(status) {
  if (status === "success") 
  {
      if (page.injectJs('jquery.js')) {
        var title = page.evaluate(function() {
          // returnTitle is a function loaded from our do.js file - see below
          return returnTitle();
        });
        console.log(title);
        phantom.exit();
      }
  }
});

您也可以使用 page.libraryPath 属性 设置查找脚本的位置。