如何使用HtmlUnit处理太多的重定向

时间:2015-05-21 09:41:17

标签: java htmlunit

我正在尝试解析网站,但我遇到了Too much redirect异常。 这是我的代码:

WebClient client = new WebClient(BrowserVersion.FIREFOX_24);
HtmlPage homePage = null;
String url = "http://www.freelake.org/pages/Freetown-Lakeville_RSD/Departments/Director_of_Financial_Operatio";
try {
    client.getOptions().setUseInsecureSSL(true);
    client.setAjaxController(new NicelyResynchronizingAjaxController());
    client.getOptions().setThrowExceptionOnFailingStatusCode(false);
    client.getOptions().setThrowExceptionOnScriptError(false);
    client.waitForBackgroundJavaScript(30000);
    client.waitForBackgroundJavaScriptStartingBefore(30000);
    client.getOptions().setCssEnabled(false);
    client.getOptions().setJavaScriptEnabled(true);
    client.getOptions().setRedirectEnabled(true);
    homePage = client.getPage(url);
    synchronized (homePage) {
        homePage.wait(25000);
    }
    System.out.println(homePage.asXml());
} catch (Exception e) {
    e.printStackTrace();
}        

下面提到了例外

com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: Too much redirect for http://www.freelake.org/resolver/2345183424.20480.0000/route.00/pages/Freetown-Lakeville_RSD/Departments/Director_of_Financial_Operatio
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1353)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1371)

有没有办法解决这个问题?

3 个答案:

答案 0 :(得分:5)

这是因为HtmlUnit缓存了响应,并且重定向到另一个页面然后返回。

我测试了以下,它的工作原理:

client.getCache().setMaxSize(0);

答案 1 :(得分:1)

我遇到了同样的问题,但我是通过Selenium这样做的。在Selenium中,您无法直接访问WebClient,因为它是protected

我这样做了:

WebDriver driver = new HtmlUnitDriver(true) {
    {
        this.getWebClient().getCache().setMaxSize(0);
    }
};

答案 2 :(得分:0)

页面http://www.freelake.org/pages/Freetown-Lakeville_RSD/Departments/Director_of_Financial_Operatio发送2次重定向:

  1. http://www.freelake.org/GroupHome.page,然后
  2. http://www.freelake.org/pages/Freetown-Lakeville_RSD/Departments/Director_of_Financial_Operatio
  3. 使用第二个网址,它应该工作。或者寻找一种方法告诉图书馆允许一定数量的重定向;在这种情况下为2。

    编辑:这可能会有所帮助。不要自己使用这个库:

    client.getOptions().setRedirectEnabled(true);