farrusete
farrusete

Reputation: 435

phantomjs: include jquery to hide or click element

Im trying to get a screenshot from a webpage by previously hiding the cookie policy. Something like:

var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = { width: 375, height: 667 };
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A366 Safari/600.1.4';

page.onConsoleMessage = function (msg, line, source) {
    console.log('console> ' + msg);
};

var fs = require('fs');

page.open('https://www.twitter.com/mmarkmiller/status/714525180668850176', function(status) {
    console.log('Status: ' + status);
    page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
        (page.evaluate(function() {
            console.log('Evaluating!');
            // jQuery is loaded, now manipulate the DOM
            var $button = $('div[jsnamespace="EuCookieSheet"]');
            $button.hide();
        }));
    });
    fs.write('test.html', page.content, 'w');
    page.render('teto.png');
    phantom.exit();
});

But I get no "Evaluating!" text in console log displayed and both rendered html and png files have the cookies policy visible. I see that jquery is included at the end of body in saved html but seems that the page.evaluate part is not working

What could i be missing?

Thanks!

Upvotes: 0

Views: 488

Answers (1)

user4535610
user4535610

Reputation:

There Jquery is already exist, open the console of your browser and execute $. Due to it, your callback page.includeJs won't work. You already can use jquery there, inside of evaluate context.

And also: there is no css selector like div[jsnamespace="EuCookieSheet"], you can do what you want on pure js:

function click(sel){var event=document.createEvent('MouseEvents');event.initMouseEvent('click',1,1,window,1,0,0,0,0,0,0,0,0,0,null);document.querySelector(sel).dispatchEvent(event);}
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = { width: 375, height: 667 };
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A366 Safari/600.1.4';

page.onConsoleMessage = function (msg, line, source) {
    console.log('console> ' + msg);
};

var fs = require('fs');

page.open('https://www.twitter.com/mmarkmiller/status/714525180668850176', function(status) {
    console.log('Status: ' + status);
        page.evaluate(function(click){
       console.log('Evaluating!');
        document.querySelector('div[jsnamespace="EuCookieSheet"]').style="display: none;"
        },click);
    fs.write('test.html', page.content, 'w');
    page.render('teto.png');
  phantom.exit();
})

Upvotes: 1

Related Questions