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?

Answers


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


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

Need Your Help

Unexpected behavior with Javascript object literal notation

javascript object-literal

I've been experimenting with using Javascript object literal notation vs functions with prototypes and have run into a bug I can't figure out.

My neutral Ok button is not showing in my alert dialog for Samsung S5 and J700

android

Trying to build a mobile application and have tested across some devices, but when it comes to Samsung S5 Notebook and J700 mobile phones, both have been failing because they have failed to display...