HTMLUnit Java太旧的浏览器

时间:2017-01-22 16:20:24

标签: java htmlunit

我正在尝试编写自动更新页面内容的应用程序(在我的帐户中)。我使用HTMLUnit,因为它支持javascript。 但是我遇到了“你的浏览器太老了”的问题。

我的代码:

public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);
        try (final WebClient client = new WebClient(BrowserVersion.FIREFOX_45)) {
            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);

            HtmlPage page = client.getPage("https://passport.yandex.ru/passport?mode=auth&retpath=https://toloka.yandex.ru/?ncrnd=5645");

            HtmlForm form = page.getForms().get(0);

            HtmlInput inputLogin = form.getInputByName("login");

            inputLogin.setValueAttribute(userName);
            HtmlInput inputPassw = form.getInputByName("passwd");

            inputPassw.setValueAttribute(password);

            DomElement button = page.getElementsByTagName("button").get(0);
            HtmlPage page2 = button.click();

            System.out.println(page2.asXml());
        }
        catch (IOException e) {

        }
    }

登录成功,但我无法加载第二页。 (它应该重定向到内容页面)

答案:

<h1 style="padding-top: 20px;">Browser is too old</h1>
    <p>
        Unfortunately you are using an old browser.
        Please, upgrade to at least IE10 or use one of the modern browsers, e.g.
        <a href="http://browser.yandex.net/">Yandex.Browser</a>,
        <a href="https://www.google.com/chrome/browser/">Google Chrome</a> or
        <a href="https://www.mozilla.org/firefox/new/">Mozilla Firefox</a>
    </p>

我该如何解决?感谢。

1 个答案:

答案 0 :(得分:1)

您的问题没有简单的解决方案,但您可以做一些事情。

  1. 使用HtmlUnit(http://htmlunit.sourceforge.net/gettingLatestCode.html
  2. 的最新快照构建
  3. 尝试使用不同的模拟浏览器(例如chrome)
  4. 清理您的客户端设置,只设置所需的选项(在您的情况下可能是setUseInsecureSSL(true);
  5. waitForBackgroundJavaScript和waitForBackgroundJavaScriptStartingBefore都没有选项;在客户端设置中执行此操作是无用的
  6. 检查你的日志;也许有一些关于不支持javascript方法的提示
  7. 点击按钮后调用waitForBackgroundJavaScript; mabey重定向由一些javascript完成,但延迟很短。

    HtmlPage page2 = button.click();
    client.waitForBackgroundJavaScript(30000);
    

    因为javascript可能会更改页面内容,所以您必须再次获取页面内容。

    page2 = page2.getEnclosingWindow().getEnclosedPage();
    

    通常,对浏览器版本的检查是通过一些javascript魔术完成的。也许HtmlUnit没有(正确)支持/模拟您的网站使用的魔术。如果您能够找到根本原因,可以填写错误(请参阅http://htmlunit.sourceforge.net/submittingJSBugs.html以获取有关如何找到此错误的一些提示)。