nail181
nail181

Reputation: 11

HtmlUnit, Trying to get the form but getting an error


import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;


public class Main {

    public static void main(String[] args) {
        WebClient webClient = new WebClient();
        webClient.getOptions().setThrowExceptionOnScriptError(false);

        try {
            HtmlPage page = (HtmlPage) webClient
                    .getPage("https://www.reddit.com/login");
            HtmlForm form = page.getFormByName("AnimatedForm");
            form.getInputByName("username").setValueAttribute("myUsername");
            HtmlInput passWordInput = form.getInputByName("password");
            passWordInput.removeAttribute("disabled");
            passWordInput.setValueAttribute("myPassword");

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

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

}

Everytime I run this I get an error saying "com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[form] attributeName=[name] attributeValue=[AnimatedForm]." It seems to not recognize the AnimatedForm. I was just wondering why.

Upvotes: 0

Views: 290

Answers (2)

Rob Evans
Rob Evans

Reputation: 2874

You're really going to struggle to get the login to work with Reddit. Its not a simple process. If you try it manually, the login submits credentials and it looks like you get a response in the browser asynchronously, without being immediately redirected. In fact it takes around 5 seconds before the user is redirected to the main landing page in a browser.

I'd highly recommend you look at utilising an already available API rather than trying to implement a login process (I've tried it and work with HTTP protocol a fair bit day to day building web services... its not simple).

Useful resources: Reddit library you could use in a Java project https://github.com/ViteFalcon/reddit4j (not tested myself but worth a try)

Reddit Api: https://www.reddit.com/dev/api/

Upvotes: 0

vitalyster
vitalyster

Reputation: 5266

The method you are using page.getFormByName("AnimatedForm") will search for <form> having attribute name="AnimatedForm".

There is no form with the name "AnimatedForm" on the page, I see a form with class="AnimatedForm". To retrieve element by class use something like page.getByXPath("//div[@class='AnimatedForm']")

Upvotes: 1

Related Questions