Skip to content Skip to sidebar Skip to footer

Java – How Can I Log Into A Website With Htmlunit?

I am writing a Java program to log into the website my school uses to post grades. This is the url of the login form: https://ma-andover.myfollett.com/aspen/logon.do This is the HT

Solution 1:

The password field is disabled until you type something in the username field. By setting the value in username doesn't trigger the event that manages the enabling of password field.

The below works

publicstaticvoidmain(String[] args) {
    WebClientwebClient=newWebClient();
    try {
        HtmlPagepage= (HtmlPage) webClient
                .getPage("https://ma-andover.myfollett.com/aspen/logon.do");
        HtmlFormform= page.getFormByName("logonForm");
        form.getInputByName("username").setValueAttribute("myUsername"); 
        HtmlInputpassWordInput= form.getInputByName("password");
        passWordInput.removeAttribute("disabled");
        passWordInput.setValueAttribute("myPassword"); 

        page = form.getInputByValue("Log On").click(); // works fine

        System.out.println(page.asText());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        webClient.close();
    }
}

The output is

Aspen: Log On

Aspen

    About Aspen
Andover Public Schools
Login ID myUsername  
Password I forgot my password
Log On

Copyright © 2003-2014 Follett School Solutions. All rights reserved.
Follett Corporation Follett Software Company Aspen Terms of Use

Invalid login.  
OK

Solution 2:

To automatically handle the JavaScript, you should use type() instead.

try (WebClientwebClient=newWebClient()) {

    HtmlPagepage= (HtmlPage) webClient.getPage("https://ma-andover.myfollett.com/aspen/logon.do"); 
    HtmlFormform= page.getFormByName("logonForm"); 
    form.getInputByName("username").type("myUsername"); 
    form.getInputByName("password").type("myPassword"); 

    page = form.getInputByValue("Log On").click();

    System.out.println(page.asText());
}

Solution 3:

I used:

finalWebClientwebClient=newWebClient())    
HtmlPagepage= webClient.getPage("url");

((HtmlTextInput) page.getHtmlElementById("usernameID")).setText("Username");
page.getHtmlElementById("passwordID").setAttribute("value","Password");

page.getElementsByTagName("button").get(0).click();

System.out.println(page.asText());

I clicked the button that way because my button doesn't have an id, name, or value, but luckily its the only button on the page. So I just get all the button tags (all one of them) and select the first element in the List to click.

Post a Comment for "Java – How Can I Log Into A Website With Htmlunit?"