【问题标题】:Can't take a screenshot on instagram.com with Phantomjs code example, why it's always a black screen?无法使用 Phantomjs 代码示例在 instagram.com 上截屏,为什么总是黑屏?
【发布时间】:2018-07-05 12:41:28
【问题描述】:

这是我的phantomjs超级简单代码(test2.js):

var page = require('webpage').create();
page.open('https://instagram.com', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    page.render('example.png');
  }
  phantom.exit();
});

cmd代码:

phantomjs.exe --ignore-ssl-errors=true  test2.js

结果 - 始终为黑色屏幕截图,空白

【问题讨论】:

  • 它可能是在完全加载之前捕获屏幕截图,设置条件检查元素是否加载然后调用渲染。
  • 另外:您应该使用真实的用户代理,将视口设置为真实屏幕尺寸(默认为 400x300),并可能使用page.onError 回调来检查错误。

标签: javascript selenium phantomjs casperjs


【解决方案1】:

问题是,当您截取屏幕截图时,该页面尚未处理。您应该等待页面完全加载(使用 javascript 处理)。您可以通过更改此行来简单地检查一下:

page.render('example.png');

到这样的事情:

window.setTimeout(function(){
   page.render('example.png');
   phantom.exit();
},15000);

请注意,等待给定的时间不是一个好主意...最好使用一些 WaitFor 函数...

例如:

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 5000, //< Default Max Timout is 5s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("  * Timeout, exiting.");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 250); //< repeat check every 250ms
};

示例用法:

waitFor(function(){
    page.evaluate(function(){
        return ((document.documentElement.textContent || document.documentElement.innerText).indexOf('© 2018 INSTAGRAM') > -1); // <-- this may be some other string or other condition - don't know instagram site at all... generally it should return true if the element was found and false if not.
    });
    },function(){       
        page.render('example.png');
    }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    相关资源
    最近更新 更多