2016-11-17 220 views
7

我试图抓取使用htmlunit的网站。每当我运行它,虽然它只是输出下列错误:htmlunit无法从undefined读取属性“推”

Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Cannot read property "push" from undefined (https://www.kinoheld.de/dist/prod/0.4.7/widget.js#1) 

现在我不知道很多关于JS,但我读了push是某种数组的操作。这对我来说似乎是标准的,我不知道为什么它不会被htmlunit支持。

这里是代码我使用至今:

public static void main(String[] args) throws IOException { 
    WebClient web = new WebClient(BrowserVersion.FIREFOX_45); 
    web.getOptions().setUseInsecureSSL(true); 
    String url = "https://www.kinoheld.de/kino-muenchen/royal-filmpalast/vorstellung/280823/?mode=widget&showID=280828#panel-seats"; 
    web.getOptions().setThrowExceptionOnFailingStatusCode(false); 
    web.waitForBackgroundJavaScript(9000); 
    HtmlPage response = web.getPage(url); 

    System.out.println(response.getTitleText()); 
} 

我缺少什么?有没有办法解决这个问题呢? 在此先感谢!

+1

如果不支持,我想你应该向开发人员申请一个新功能。 –

+0

何时发生错误?在'web.getPage(url)'或者'response.getTitleText()'调用之后? – Jack

+0

@Jack'web.getPage(url)'后出现错误,因为我可以注释掉'response.getTitleText()'并且它仍然会被抛出,即使当'web.getOptions()。setThrowExceptionOnScriptError(false );'(见下面的答案)被插入。 – Maverick283

回答

4

我以前也遇到过类似的问题。这是HTML单元被设计为测试工具框架而不是网页抓取的问题。您是否运行最新版本的HTML单元?

我能够加入两个setThrowExceptionOnScriptError(false)(如咖啡转换器的答复中提到)线,以及在该方法的顶部添加 java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF); 禁用日志转储到运行代码。这产生的输出:

Royal Filmpalast München München | kinoheld.de 

完整代码如下:

public static void main(String[] args) throws IOException { 

    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF); 

    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45); 
    String url = "https://www.kinoheld.de/kino-muenchen/royal-filmpalast/vorstellung/280823/?mode=widget&showID=280828#panel-seats"; 

    webClient.getOptions().setUseInsecureSSL(true); 
    webClient.getOptions().setThrowExceptionOnScriptError(false); 
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); 
    webClient.waitForBackgroundJavaScript(9000); 
    HtmlPage response = webClient.getPage(url); 

    System.out.println(response.getTitleText()); 
} 

这是在RedHat命令行与HTML单元2.2.1运行。希望这可以帮助。

6

尝试增加

web.getOptions().setThrowExceptionOnScriptError(false); 

您尝试获取页面之前。这迫使htmlunit忽略错误。但是,这可能无法100%的时间,例如,如果引发错误的JavaScript是非常重要的,以获取您要废弃的数据(它希望不是)。如果这不起作用,请尝试在ChromeDriver或GhostDriver中使用Selenium。

Source

+0

添加该行不起作用,它仍会抛出相同的错误,并且不会将我带到任何地方......我会尝试任何Selenium稍后的更多时间;) – Maverick283

+0

但是在原始异常处于堆栈之前用你建议的那一行跟踪,它现在说'com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify',然后打印剩下的堆栈跟踪。 – Maverick283

+2

我真的希望我可以分50分,而@杰克的答案确实解决了问题,你的建议可能会对我的远射更有帮助... – Maverick283