2013-05-22 2 views
27

저는 PhantomJs 초보자입니다. 이 사이트에서 비슷한 게시물을 확인했습니다. 내 질문은 'foo'가 콘솔이나 인쇄물에 기록되지 않는 이유입니다.phantomjs page.evaluate 콘솔에 로그온하지 않습니다.

var page = require('webpage').create() 
var foo = 42; 

function evaluate(page, func) { 
    var args = [].slice.call(arguments, 2); 
    var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}"; 
    return page.evaluate(fn); 
} 

page.open('http://google.com', function() { 
    var foo = 42; 
    evaluate(page, function(foo) { 
    console.log(foo); 
     },foo); 

}); 

답변

48

호출 page.evaluate()는 평가 된 코드를 샌드 박스에서 실행합니다. 샌드 박스의 콘솔은 PhantomJS의 콘솔과 동일하지 않습니다.

스크립트에 다음 행을 추가하면 페이지 콘솔이 stderr로 인쇄됩니다.

var system = require('system'); 

page.onConsoleMessage = function(msg) { 
    system.stderr.writeLine('console: ' + msg); 
}; 

더 완벽하게 구현은 다음과 같습니다

var page = require('webpage').create() 
var system = require('system'); 
var foo = 42; 

page.onConsoleMessage = function(msg) { 
    system.stderr.writeLine('console: ' + msg); 
}; 

function evaluate(page, func) { 
    var args = [].slice.call(arguments, 2); 
    var fn = "function() { return (" + func.toString() + ").apply(this, " +  JSON.stringify(args) + ");}"; 
    return page.evaluate(fn); 
} 

page.open(
    'http://google.com', 
    function() { 
    var foo = 42; 
    evaluate(
     page, 
     function(foo) { 
     console.log(foo); 
     }, 
     foo 
    ); 

    console.log("Done"); 

    phantom.exit(0); // must exit somewhere in the script 
    } 
); 

출력 : 당신의 URL처럼 :

$ phantomjs /tmp/idiot.js 
console: 42 
Done 

그런데를, 당신은 "빈에 대해"사용 page.open 호출 할 수 있습니다 평가 기능을 샌드 박스 테스트하고 싶을뿐입니다.

+0

방금 ​​추가했는데 아무런 문제가 없습니다. 걸려 있습니다. 심지어 종료하지 않습니다. 즉, 먼저 어떤 기능을 수행할지 알지 못합니다. page.open 또는 page.onConsoleMessage! 주요 기능이 없습니다! 디버거가 있습니까? – Raaj

+0

화난 새 'foo'변수를 여기에 놓친 것 : **'}, foo);'**. 감사. 어디에서 페이지를 얻을 수 있습니까? 기능? 그 (것)들을위한 어떤 ctags든지있다. 도구없이 실시간으로 낭비하는 이러한 자바 스크립트.파이썬에서 가져올 수있는 것은 무엇입니까? 만약 내가 어떻게 os.shell과 떨어져 파이썬으로 이러한 phantomjs 자바 스크립트를 가져올 것입니다. 나는 pyphantomjs를 시도했지만 설득력이 없습니다. – Raaj

+0

있어이 [링크] (http://stackoverflow.com/questions/13287490/is-there-a-way-to-use-phantomjs-in-python). 좋아 보인다. ajax가 값을로드 할 때까지 기다리는 지 궁금합니다. 나 해보자. – Raaj

17

표준 오류 출력이 날

작업 주위에 할당되어 작동하지 않았다

window.console.log = function(msg) { alert(msg) }; 

을 page.evaluate 내부

그런 다음 사용

page.onAlert = function(msg) { 
    console.log(msg); 
}; 

에 경고 잡기

+0

나를 위해 일했습니다. +1 –

+0

나를 위해 일했습니다. +1 – timwebdev

0

phantomjs를 사용하여 일부 Google Closure 테스트를 자동화하고 디버깅해야하는 문제가 발생했습니다. 내 테스트 페이지에서 맞춤 이벤트를 보내고 page.evaluate 안에 수신 할 수있었습니다.

파일 메시지를 기록합니다 :

function logger(msg) { 
    var evt = document.createEvent('CustomEvent'); // MUST be 'CustomEvent' 
    evt.initCustomEvent('logger', false, false, msg); 
    document.dispatchEvent(evt); 
} 

logger('my debug message'); 

Phantomjs 파일을. 여기에 saveMessage 메서드를 사용하여 문자열을 저장하지만, 사용자가 필요로하는 것을보다 적절하게 만들 수 있습니다.

var exec = page.evaluate(function() { 
    window.phantomRunner = new window.goog.testing.TestRunner(); 
    window.phantomTest = new window.goog.testing.TestCase(); 

    // Listen for `logger` events. The message is stored inside the event's detail property. 
    document.addEventListener('logger', function(e) { 
    window.phantomTest.saveMessage(e.detail); 
    }); 

    window.phantomTest.autoDiscoverTests(); 
    window.phantomRunner.initialize(window.phantomTest); 
    window.phantomRunner.execute(); 
    return (window.phantomTest.result_.messages); 
}) 
0

당신의 phantomjs 설정은 자바 스크립트를 실행 해제되지 않습니다 있는지 확인

page.settings.javascriptEnabled = true; 
8

이 콘솔 로깅 과거에 몇 가지 문제가 있었지만, phantomjs의 현재 버전 (1.9.8)을 수행 할 수 있습니다 수행

page.onConsoleMessage = function (msg) { 
    console.log(msg); 
}; 

다음 evaluate의 콜백에 console.log의 멀리 화재 :

page.evaluate(function() { 
    console.log("some logged message"); 
}); 
관련 문제