HtmlUnit:点击无响应时登录 HtmlElement

HtmlUnit: login HtmlElement when click not responding

您好,这是我第一次使用 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);

}

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

编辑 1: 我已经尝试 Thread.sleep(2000) 输入用户名和密码后点击行

编辑 2: 用于登录的 js:

document.onkeypress = processKey;


function processKey(e) {
    if (null == e)
        e = window.event ;
    if (e.keyCode != 13) 
        return;
    $('button').click();
    return false;
}


function parseXMLTag(tag) {
    var value = '';
    if (tag && tag.firstChild != undefined) {
        value = tag.firstChild.nodeValue;
    }
    return value;
}


function login() {
    new Ajax.Request('/cti/api/admin/login.xml', {
        method: 'post',
        parameters: {username: $('username').value, password: $('password').value},
        onSuccess: function(transport) {
            var response = transport.responseXML;
            var success = parseXMLTag(response.firstChild.getElementsByTagName('success')[0]);
            var error = parseXMLTag(response.firstChild.getElementsByTagName('error')[0]);
            if (success == 1)
                document.location = 'main.html';
            else
                $('error').innerHTML = error;
        }
    }); 
}

我建议您尝试设置:

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

由于您没有发布您所拨打的url,我只能提供一些提示。

即使 HtmlUnit 在幕后做了很多魔术,您也需要对所有网络技术有基本的了解

从代码看来,登录是基于Ajax完成的;这有一些含义:

  • Ajax 需要启用 javascript(HtmlUnit 默认值)
  • Ajax 是异步的 - HtmlUnit 中的所有操作(例如单击)都是同步的,这意味着您必须等待 ajax 调用完成
  • 在您的特殊情况下,ajax 调用会通过使用不同的 url(document.location = 'main.html')重新加载页面来成功更改页面的内容。因此,您必须刷新页面变量

或者在代码中:

try (WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52))
{
    webClient.getOptions().setUseInsecureSSL(true);

    HtmlPage page = webClient.getPage(url);
    String pageContent = page.asText();
    System.out.println(pageContent);

    HtmlButtonInput button = page.getFirstByXPath("//input[@type = 'button']");
    // to make sure you got the right element
    System.out.println(button.asXml());

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

    // use type() to simulate typing
    name.type(username);
    pwd.type(password);

    // no need to get the page here because this is still the one the
    // button is placed on
    button.click();

    // wait for ajax to do the job
    webClient.waitForBackgroundJavaScript(10000);


    // ok hopefully the job is done and the login was successfull
    // lets get the current page out of the current window
    HtmlPage loggedInPage = (HtmlPage) page.getEnclosingWindow().getTopWindow().getEnclosedPage();

    ...

    // check the result
    // you can also write this to a file and open it in a real browser
    // maybe the login was failing and there is an error message
    // rendered on this page
    System.out.println(loggedInPage.asXml());

}

希望对您有所帮助。