HTMLUnit 的密码设置问题

Problems with Password setting with HTMLUnit

这是我的 Class,应该通过在其字段中设置特定的用户名和密码来登录网站。 运行 它一直有效,直到它设置了用户名,但 finding/filling 密码框似乎有问题。 我仔细检查了 HTML 以确保我输入了正确的密码框名称,但仍然无法正常工作。 感谢帮助

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class FormSubmit {

    public static void main(String[] args){
        submittingForm();
    }

    public static void submittingForm() {

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



        try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {

            webClient.getCookieManager().setCookiesEnabled(true);
            webClient.setJavaScriptEnabled(true);

            final HtmlPage page1 = webClient.getPage("website");

            final HtmlForm form = page1.getFormByName("formname");

            final HtmlSubmitInput loginButton = form.getInputByName("inputname");
            final HtmlTextInput username = form.getInputByName("name");

            username.setValueAttribute("namevalue");         
            System.out.println(username);

            final HtmlTextInput password = form.getInputByName("password");
            password.removeAttribute("disabled");
            password.setValueAttribute("passvalue");
            System.out.println(password);

            final HtmlPage page2 =  (HtmlPage) form.getInputByValue(" Login ").click();
            System.out.println(page2.getBody());
        }
        catch (Exception e){
        }
    }
}

我猜你使用的是 API 用法中的旧 HmltUnit 版本,请更新你的版本(最好是 latest build)。

以下代码有效:

请注意:

  1. 默认情况下启用 Cookie 和 JavaScript,您无需将它们设置为 true
  2. password 输入应该是 HtmlPasswordInput,否则你会得到 ClassCastException


public class FormSubmit {

    public static void main(String[] args) throws Exception {
        try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
            final HtmlPage page1 = webClient.getPage("https://applicazioni.gse.it/GWA_UI/");

            System.out.println(page1.asXml());
            final HtmlForm form = page1.getFormByName("aspnetForm");

            final HtmlTextInput username = form.getInputByName("ctl00$ctl00$cphFormAppl$cphRisultatiRicerca$txtUserid");

            username.setValueAttribute("namevalue");         

            final HtmlPasswordInput password = form.getInputByName("ctl00$ctl00$cphFormAppl$cphRisultatiRicerca$txtPassword");
            password.setValueAttribute("passvalue");

            final HtmlPage page2 = (HtmlPage) form.getInputByValue(" Login ").click();
            System.out.println(page2.asText());
        }
    }
}