pguardiario
pguardiario

Reputation: 55002

How to use jQuery with phantomjs

I'm trying to do a simple test of jQuery with phantomjs:

var url = 'http://www.google.com/';
var page = require('webpage').create();
page.open(url, function () {
    page.injectJs('jquery.min.js');
    page.evaluate(function () {
        console.log($('title').text());
    });
    phantom.exit()
});

This should print out the title, but instead nothing happens. Can somebody tell me what's wrong?

Upvotes: 2

Views: 4770

Answers (2)

Vitaly Slobodin
Vitaly Slobodin

Reputation: 1359

page.evaluate executes your function in the page context, not in the PhantomJS context. So, everything that uses console will be printed (and will be visible) only for current Web Page instance.

To redirect the console output, you must use onConsoleMessage callback.

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

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

page.open(url, function () {
    page.injectJs('jquery.min.js');
    page.evaluate(function () {
        console.log($('title').text());
    });
    phantom.exit()
});

Reference: onConsoleMessage

Upvotes: 3

Felix
Felix

Reputation: 38112

Seem like you're missing # to target element by id:

console.log($('#title').text());
// -----       ^ add here

if title is a class then you can use .:

console.log($('.title').text());

Upvotes: 0

Related Questions