virtual web browser submit using HtmlUnit + Java
I'm trying to sign in to yahoo.com using HtmlUnit. But it doesn't work when my program trying to click "Sign In" button. My code is:
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;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import java.io.IOException;
import java.net.URL;
public class MyBrowser {
public void homePage() throws Exception {
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setThrowExceptionOnScriptError(false);
webClient.setRefreshHandler(new RefreshHandler() {
public void handleRefresh(Page page, URL url, int arg) throws IOException {
System.out.println("handleRefresh");
}
});
HtmlPage page = (HtmlPage) webClient.getPage("https://login.yahoo.com/config/login?.src=fpctx&.intl=us&.done=http%3A%2F%2Fwww.yahoo.com%2F");
HtmlForm form 开发者_Go百科= page.getFormByName("login_form");
form.getInputByName("login").setValueAttribute("@@@@@@"); // works OK
form.getInputByName("passwd").setValueAttribute("@@@@@@"); // works OK
page = (HtmlPage) form.getInputByValue("Sign In").click(); // doesn't work
webClient.closeAllWindows();
}
}
Error:
com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[input] attributeName=[value] attributeValue=[Sign In]
at com.gargoylesoftware.htmlunit.html.HtmlForm.getInputByValue(HtmlForm.java:737)
Form is:
<form method="post" action="https://login.yahoo.com/config/login?" autocomplete="" name="login_form" onsubmit="return hash2(this)">
...
<div id="submit">
<button type="submit" id=".save" name=".save" class="primaryCta" tabindex="5"> Sign In </button>
</div>
</form>
I do know nothing about HtmlUnit, but from the error message it looks like the it searches for some element with a value
attribute, and your button has no such attribute. Maybe byName
or such? And it is not a <input>
element, but a <button>
element, so maybe something like getButtonByName(".save")
?
Edit: I found the Javadoc, and seems I guessed the method name right :-p
The Yahoo login form submit button has a name specification, not a value specification. You need to get the input by name. I suggest that you change:
page = (HtmlPage) form.getInputByValue("Sign In").click();
...to...
page = (HtmlPage) form.getInputByName("Sign In").click();
精彩评论