phantomjs:包含要隐藏或单击元素的jquery

时间:2016-11-18 09:53:44

标签: javascript jquery phantomjs

我试图通过先前隐藏Cookie政策从网页获取屏幕截图。类似的东西:

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

但我没有“评估!”显示控制台日志中的文本,并且呈现的html和png文件都具有可见的cookie策略。我看到jquery包含在保存的html中的body的末尾但似乎page.evaluate部分不起作用

我能错过什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

Jquery已经存在,打开浏览器的控制台并执行$。因此,您的回调page.includeJs无法正常工作。您已经可以在评估上下文中使用jquery。

而且:没有像div[jsnamespace="EuCookieSheet"]这样的css选择器,你可以在纯粹的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();
})