调试PhantomJS webpage.open的失败[英] Debugging PhantomJS webpage.open failures

问题描述

在 PhantomJS 中,webpage.open 接受一个带有设置为"成功"或"失败"的状态参数的回调.根据文档,如果没有发生网络错误,它将是"'成功',否则'失败'."有没有办法查看导致失败的底层网络错误?

我尝试加载的网址在我的浏览器中运行良好,当我在收到"失败"消息后截取屏幕截图时,我看到了我在调用 pages.open 之前所在的页面(所以我不能忽略失败).我正在使用 Phantom 进行测试,所以理想情况下,我想要一种强大的方法,可以在 pages.open 失败时轻松获得有用的错误消息(或者更好的是永远不会失败!)

推荐答案

发现这篇文章解释了如何设置回调以了解失败的根本原因:http://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/

根据该页面,您可以打印出如下错误:

page.onResourceError = function(resourceError) {
    console.error(resourceError.url + ': ' + resourceError.errorString);
};

该页面继续显示幻影的详细日志记录示例

var system = require('system');

page.onResourceRequested = function (request) {
    system.stderr.writeLine('= onResourceRequested()');
    system.stderr.writeLine('  request: ' + JSON.stringify(request, undefined, 4));
};

page.onResourceReceived = function(response) {
    system.stderr.writeLine('= onResourceReceived()' );
    system.stderr.writeLine('  id: ' + response.id + ', stage: "' + response.stage + '", response: ' + JSON.stringify(response));
};

page.onLoadStarted = function() {
    system.stderr.writeLine('= onLoadStarted()');
    var currentUrl = page.evaluate(function() {
        return window.location.href;
    });
    system.stderr.writeLine('  leaving url: ' + currentUrl);
};

page.onLoadFinished = function(status) {
    system.stderr.writeLine('= onLoadFinished()');
    system.stderr.writeLine('  status: ' + status);
};

page.onNavigationRequested = function(url, type, willNavigate, main) {
    system.stderr.writeLine('= onNavigationRequested');
    system.stderr.writeLine('  destination_url: ' + url);
    system.stderr.writeLine('  type (cause): ' + type);
    system.stderr.writeLine('  will navigate: ' + willNavigate);
    system.stderr.writeLine('  from page\'s main frame: ' + main);
};

page.onResourceError = function(resourceError) {
    system.stderr.writeLine('= onResourceError()');
    system.stderr.writeLine('  - unable to load url: "' + resourceError.url + '"');
    system.stderr.writeLine('  - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString );
};

page.onError = function(msg, trace) {
    system.stderr.writeLine('= onError()');
    var msgStack = ['  ERROR: ' + msg];
    if (trace) {
        msgStack.push('  TRACE:');
        trace.forEach(function(t) {
            msgStack.push('    -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
        });
    }
    system.stderr.writeLine(msgStack.join('\n'));
};

本文地址:https://www.itbaoku.cn/post/1739925.html