首页 > 解决方案 > 使用 Java 和 htmlUnit 查找表单

问题描述

我编写了一个简单的程序,它应该通过网站上的表单登录。

不幸的是,html 中的表单没有名称或 ID。

我使用最新版本的 HtmlUnit 和 Java 11。

我尝试使用 .getForms () 方法查找表单,但没有成功。

来自网站的 Html Snippet 我尝试登录

这是我查找表单的代码:

    //Get the form
     HtmlForm form = LoginPage.getFormByName("I tried several options here");
    //Get the Submit button
    final HtmlButton loginButton = form.getButtonByName("Anmelden");
    //Get the text fields for password and username
    final HtmlTextInput username = form.getInputByName("text");
    final HtmlTextInput password = form.getInputByName("password");

无论我尝试什么,我都没有找到任何形式。

如果有帮助,这是我的连接类:

 public HtmlPage CslPlasmaConnection(){
    //Create Webclient to connect to CslPlasma
    WebClient CslPlasmaConnection = new WebClient(BrowserVersion.BEST_SUPPORTED);
    //helper variable ini with null
    HtmlPage CslPlasmaLoginPage = null;
    //Get the content from CslPlasma

    try {
        CslPlasmaLoginPage = CslPlasmaConnection.getPage(URL);

    } catch (IOException e) {
        e.printStackTrace();
    }
    //Return CslPlasma Login Page
    return CslPlasmaLoginPage;
}

标签: javahtmlhtmlunit

解决方案


在不知道页面的情况下,我只能猜测...

看看这个答案https://stackoverflow.com/a/54188201/4804091

并尝试使用最新的页面(可能有一些创建表单的 js)。

    webClient.getPage(url);
    webClient.waitForBackgroundJavaScript(10000);

    HtmlPage page = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();

推荐阅读