how to ignore errors in phantomjs

2020-02-23 06:36发布

问题:

I have a web crawler and I use phantomjs to parse pages, I want to get the html, but I always get this type of errors in the output before the html code

ReferenceError: Can't find variable: collapse_content_selector

  http://staticloads.com/js/toggle.js?v=2013.10.04:135
TypeError: 'undefined' is not a function (evaluating '$('[placeholder]').placeholderLabel()')

how can I stop that

回答1:

The easiest way is to add an error handler to phantom.onerror or webpage.onerror. These callbacks are invoked when there is a JavaScript execution error (in the page or in your script).

page.onError = function(msg, trace) {
    var msgStack = ['ERROR: ' + msg];
    if (trace && trace.length) {
        msgStack.push('TRACE:');
        trace.forEach(function(t) {
            msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
        });
    }
    // uncomment to log into the console 
    // console.error(msgStack.join('\n'));
};