Guilherme Salome
Guilherme Salome

Reputation: 2049

PhantomJS + jQuery -> Can't get image

PROBLEM: the function inside page.evaluate doesn't find any img (therefore, console.log(images.length) outputs 0); however, there are many images in the page, and some even have ids.

QUESTION: What's going on? Why $('img') doesn't find anything?

UPDATE 1: This is a <frame> problem. I had to switch to the frame in order to make the jQuery script correctly work.

DETAILS: I'm running a phantomjs script to access a webpage (link) and fetch all available images. It first saves a screenshot of the page just for comparison, and then it should through every <img> tag (using jQuery $('img')) and get the image dimensions and, using phantomjs's page.clipRect, it saves each image inside a folder.

var page = require('webpage').create();
var url = 'http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp';

page.open(url, function (status) {

    console.log("Status: " + status);
            if (status === "success") {
        page.render('example.png');
    }

    // Asynchronous call!
    page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function () {

        console.log('\n Evaluate Page \n');
        // Sandboxed
        var images = page.evaluate(function () {
            var images = [];
            function getImgDimensions($i) {
                return {
                    top: $i.offset().top,
                    left: $i.offset().left,
                    width: $i.width(),
                    height: $i.height(),
                }
            }
            $('img').each(function () {
                var img = getImgDimensions($(this));
                images.push(img);
            });

            return images;
        });
        console.log(images.length);


        images.forEach(function (imageObj, index, array) {
            page.clipRect = imageObj;
            page.render('images/' + index + '.png');
        });

        // Exit the session
        phantom.exit();
    });
});

Upvotes: 0

Views: 312

Answers (1)

Artjom B.
Artjom B.

Reputation: 61952

I've looked at the site. The img that you want is inside of an iframe. You first need to switch to it.

Use for example:

page.switchToChildFrame(0);

to switch to the first child frame. Do this before you call page.includeJs().

If you want to do something in the parent page afterwards, you would have to change back with page.switchToParentFrame();.

Upvotes: 2

Related Questions