Java HtmlUnit用户名和密码登录返回登录页
问题描述:
我想用有效的用户名和密码使用HtmlUnit执行登录。成功登录后,我想在结果页面上执行一些操作。问题是我无法通过登录阶段 - 我一直在同一页面。奇怪的是,我记录了HtmlUnit Scripter Firefox插件的成功登录,然后重播了结果代码 - 同样的问题。有任何想法吗?Java HtmlUnit用户名和密码登录返回登录页
下面是代码:
<pre>
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.io.IOException;
import java.net.MalformedURLException;
<code>
public class LoginSimulation
{
public static void main(String args[])
{
HtmlPage page = null;
String url = "http://www.ravmilim.co.il/naerr.asp";
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setThrowExceptionOnScriptError(false);
try
{
page = webClient.getPage(url);
HtmlTextInput userInput = (HtmlTextInput) page.getElementById("txtUser");
userInput.setValueAttribute("[email protected]");
HtmlPasswordInput passwordInput = (HtmlPasswordInput) page.getElementById("txtPass");
passwordInput.setValueAttribute("5750201");
HtmlElement theElement2 = (HtmlElement) page.getElementById("submitButton");
page = theElement2.click(); // the login does not work. Login page is displayed again
System.out.println(page.asText());
webClient.closeAllWindows();
}
catch (FailingHttpStatusCodeException e1)
{
System.out.println("FailingHttpStatusCodeException thrown:" + e1.getMessage());
e1.printStackTrace();
}
catch (MalformedURLException e1)
{
System.out.println("MalformedURLException thrown:" + e1.getMessage());
e1.printStackTrace();
}
catch (IOException e1)
{
System.out.println("IOException thrown:" + e1.getMessage());
e1.printStackTrace();
}
catch(Exception e)
{
System.out.println("General exception thrown:" + e.getMessage());
e.printStackTrace();
}
}
}
答
看起来你的代码就可以了。我已经手动尝试过,有时会记录,有时候不会。问题出在登录操作后出现的弹出窗口中。 你可以看到它从页面上的JavaScript:
if ($("#ErrorDuplicationLogin").text() != '')
{
$(".PopUpContent").show();
$(".pagePopBackground").show();
}
});
所以尝试登录和注销手动,之后启动程序。另外不要忘记使用HtmlUnit注销。谢谢。
你是对的!我注销了其他客户端,并等待先前的htmlunit登录过期,然后我才能够登录!虽然我的问题还没有结束。在下一页中,我试图设置搜索框的值,单击搜索按钮并解析结果。问题是结果显示在另一个框架中,我无法获得其他框架。这里是修改后的代码: – user2045777
System.out.println(page.asText())之后 - 我添加了: – user2045777
HtmlPage framePage =(HtmlPage)nextPage.getFrames()。get(0).getEnclosedPage(); HtmlTextInput searchBox =(HtmlTextInput)framePage.getForms()。get(0).getInputsByName(“searchBox”)。get(0); searchBox.setValueAttribute(“word”); HtmlAnchor anchor = framePage.getHtmlElementById(“sl”); HtmlPage page1 =(HtmlPage)anchor.click(); try { HtmlPage resultsPage =(HtmlPage)page1.getFrameByName(“resault1”)。getEnclosedPage(); (例外e){ e.printStackTrace(); } framePage.getAnchorByHref(“logout.asp”)。click(); – user2045777