HtmlUnit:单击“不响应”时登录HtmlElement怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (193)

我第一次使用HtmlUnit版本2.31,我正在尝试登录到一个网页。下面是HTML:

<body>
    <div id="login">
        <div id="header">
            User Log In
        </div>
        <div id="error">Enter your credentials to login</div>
        <table>
            <tr>
                <th>Username</th>
                <td><input type="text" id="username" /></td>
            </tr>
            <tr>
                <th>Password</th>
                <td><input type="password" id="password" /></td>
            </tr>
        </table>
        <div id="buttons">
            <input type="button" value="Login" id="button" onclick="login();" />
        </div>
    </div>
</body>

这是我的代码:

 WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
 webClient.getOptions().setJavaScriptEnabled(false);
 webClient.getOptions().setUseInsecureSSL(true);
 try{            
        HtmlPage page = webClient.getPage(url);
        String pageContent = page.asText();
        System.out.println(pageContent);
        HtmlButtonInput button = page.getFirstByXPath("//input[@type = 'button']");
     //I'm new to XPath, but I think this works okay


        HtmlTextInput name  = (HtmlTextInput) page.getElementById("username"); 
        HtmlPasswordInput pwd  = (HtmlPasswordInput) page.getElementById("password");

        System.out.println(name.getSelectedText());
        name.setValueAttribute(username);
        pwd.setValueAttribute(password);
        System.out.println(name.getSelectedText());

        HtmlPage loggedInPage = button.click();
        String pageContent2 = loggedInPage.asText();
        System.out.println("after logged in");
        System.out.println(pageContent2);

}

两个页面(登录前和登录后)打印出来的页面都是相同的。所以我在这里一定做错了什么。任何帮助都将不胜感激。

提问于
用户回答回答于

我建议你试着设置:

 webClient.getOptions().setJavaScriptEnabled(true);
 webClient.getOptions().setRedirectEnabled(true);

扫码关注云+社区

领取腾讯云代金券