幻影 - 处理网络错误

PhantomJS - Handling Network Error

本文关键字:错误 网络 处理 幻影      更新时间:2023-09-26

当我在调试模式下运行PhantomJS脚本时,有时会看到此错误:[调试]网络 - 资源请求错误:5("操作已取消")。

当我运行脚本 1000 次时,出现此错误 1 或 2 次。我想在不以调试模式运行脚本的情况下捕获它,但我不知道如何!

我尝试了几个错误处理程序:

phantom.onError = function(msg, trace) {
  console.log("PhantomJS onError'n");
};
page.onError = function(msg, trace) {
  console.log("PhantomJS onError'n");
};
page.onResourceError = function(resourceError) {
  console.log("PhantomJS onResourceError'n");
};
page.onResourceTimeout = function(req) {
  console.error('PhantomJS onResourceTimeout'n');
};
page.onLoadFinished = function(status) {
  if (status != 'success') {
    console.error('PhantomJS onLoadFinished Error'n');
  }
};

你对我有什么想法吗?如何捕获此错误?我在Unix上使用PhantomJS 1.9.7 x64。

谢谢

这个问题可能很旧,但我今天遇到了同样的麻烦,并找到了解决方法:

var numberOfRequests = 0;
page.onResourceReceived = function(response) {
    if (numberOfRequests === 0) {
        // if status of first resource is NULL there was a network error
        if (response.status === null) {
            console.log('[ERROR] Loading page failed: Network error');
            phantom.exit();
        }
    }
    numberOfRequests++;
};

使用 phantomJS 2.1 进行测试。希望这对其他人有所帮助。