HtmlUnit 忽略 JavaScript 错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21294707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:56:11  来源:igfitidea点击:

HtmlUnit ignore JavaScript errors?

javahtmlunithtmlunit-driver

提问by cantread

I'm trying to traverse through a website but on one of their pages I get this error:

我正在尝试遍历一个网站,但在他们的其中一个页面上出现此错误:

EcmaError: lineNumber=[671] column=[0] lineSource=[null] name=[TypeError] sourceName=[https://reservations.besodelsolresort.com/asp/CalendarPopup.js] message=[TypeError: Cannot read property "parentNode" from undefined (https://reservations.besodelsolresort.com/asp/CalendarPopup.js#671)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot read property "parentNode" from undefined (https://reservations.besodelsolresort.com/asp/CalendarPopup.js#671)

Is there anyway I can just ignore this error? I don't particularly care if the calendar loads properly.

无论如何我可以忽略这个错误吗?我并不特别关心日历是否正确加载。

回答by cantread

You can use the following methods of HttpUnitOptionsclass:

您可以使用HttpUnitOptions类的以下方法:

//change the scriptingEnabled flag
static void setScriptingEnabled(boolean scriptingEnabled)

// Determines whether script errors result in exceptions or warning messages.
static void setExceptionsThrownOnScriptError(boolean throwExceptions)

Or enclose the problem area in try-catch block -

或者将问题区域括在 try-catch 块中 -

try {
   // code with error

}catch(e) {
   // handle error
}

回答by Matthew Molloy

Alexey's answer is for HttpUnit. For HtmlUnit the code is similar

Alexey 的答案是针对 HttpUnit。对于 HtmlUnit,代码类似

WebClient client = new WebClient();
client.getOptions().setThrowExceptionOnScriptError(false);

回答by jseteny

I tried to use Matthews answer and needed to override the newWebClient() method using the following way:

我尝试使用 Matthews 的答案,并需要使用以下方式覆盖 newWebClient() 方法:

    HtmlUnitDriver driver = new HtmlUnitDriver(true) {
        @Override
        protected WebClient newWebClient(BrowserVersion version) {
            WebClient webClient = super.newWebClient(version);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            return webClient;
        }
    };