Не могу сделать снимок экрана на instagram.com с примером кода Phantomjs, почему это всегда черный экран? - PullRequest
0 голосов
/ 05 июля 2018

Вот мой супер легкий код 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

результаты - всегда черный скриншот, пусто

1 Ответ

0 голосов
/ 05 июля 2018

Проблема в том, что эта страница еще не обработана, когда вы делаете снимок экрана. Вам следует дождаться полной загрузки страницы (с обработкой 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');
    }
);
...