【问题标题】:Phantom.js: Use locally, npm installed, jqueryPhantom.js:本地使用,安装npm,jquery
【发布时间】:2018-02-13 12:55:38
【问题描述】:

在许多链接上,他们建议加载 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呢?

【问题讨论】:

    标签: javascript jquery node.js phantomjs


    【解决方案1】:

    请看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 属性来设置查找脚本的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-24
      • 2011-12-26
      • 2017-08-25
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 2017-04-08
      • 2013-02-25
      相关资源
      最近更新 更多