Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10028

Phantom.js: Use locally, npm installed, jquery

On many many links they sugest to load jquery in order to do scraping in pages dom. The common pattern that is followed is:

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);
  }
});

But sometimes it would be by far network-wize sane to have a locally installed jquery via npm:

npm install jquery

But how do I include the local installed jquery?

Upvotes: 0

Views: 170

Answers (1)

Vaviloff
Vaviloff

Reputation: 16838

Please, see page.injectJs method: 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();
      }
  }
});

You can also use page.libraryPath property to set the place where to find a script.

Upvotes: 1

Related Questions