我正在尝试使用用户提供的登录连接到站点的应用程序。我没有任何与Java网站交互的经验,所以我搜索了一些,发现hmtlunit符合我的需求。Java HtmlUnit form.getInputByValue(“立即登录!”)。click();
但是,试图点击登录表单提交按钮时,我遇到了一个错误:
public static boolean attempt_login(String username, String password) throws ElementNotFoundException, IOException {
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setJavaScriptEnabled(false);
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(Config.LOGIN_PAGE);
List<HtmlForm> forms = page.getForms();
HtmlForm form = null;
for(HtmlForm f : forms){
if(f.getId().equals("login_form")){
form = f;
}
}
if(form == null){
throw new NullPointerException("Could not find form!");
}
form.getInputByName("username").setValueAttribute(username);
form.getInputByName("password").setValueAttribute(password);
page = (HtmlPage) form.getInputByValue("Login Now!").click();
System.out.println(page.asText());
return false;}
不知怎的,它未能找到提交按钮登录
com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[input] attributeName=[value] attributeValue=[Login Now!]
at com.gargoylesoftware.htmlunit.html.HtmlForm.getInputByValue(HtmlForm.java:737)
at domain.Helper.attempt_login(Helper.java:41)
at TesterStartUp.main(TesterStartUp.java:15)
HTML源代码:
<button type="submit" value="Login Now!" onmouseover="this.style.backgroundPosition='bottom';" onmouseout="this.style.backgroundPosition='top';" onclick="return SetFocus();">Login Now!</button>
当我搜索一个解决方案时,我发现了一些关于禁用j avascript会有所帮助。所以我告诉webclient禁用它(webClient.setJavaScriptEnabled(false);)但仍然有例外。
起初,我试图选择表单(“login_form”)时遇到了同样的问题,但是有一种方法可以获取所有表单的列表,然后查看是否有人匹配列表。我找不到提交按钮的方法,所以我希望别人知道这个问题的解决方案。
由于提前, 巨魔爵士
这不是我的webspage,所以我不能改变的HTML。我应该使用哪种方法?因为提交按钮中唯一的'唯一'项是值 – 2011-04-28 19:09:59