嗨,这是我第一次使用HtmlUnit [version 2.31],我正尝试登录到一个网页。这是HTML:
<body>
<div id="login">
<div id="header">
User Log In
</div>
<div id="error">Enter your credentials to login</div>
<table>
<tr>
<th>Username</th>
<td><input type="text" id="username" /></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" id="password" /></td>
</tr>
</table>
<div id="buttons">
<input type="button" value="Login" id="button" onclick="login();" />
</div>
</div>
</body>
这是我的代码:
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setUseInsecureSSL(true);
try{
HtmlPage page = webClient.getPage(url);
String pageContent = page.asText();
System.out.println(pageContent);
HtmlButtonInput button = page.getFirstByXPath("//input[@type = 'button']");
//I'm new to XPath, but I think this works okay
HtmlTextInput name = (HtmlTextInput) page.getElementById("username");
HtmlPasswordInput pwd = (HtmlPasswordInput) page.getElementById("password");
System.out.println(name.getSelectedText());
name.setValueAttribute(username);
pwd.setValueAttribute(password);
System.out.println(name.getSelectedText());
HtmlPage loggedInPage = button.click();
String pageContent2 = loggedInPage.asText();
System.out.println("after logged in");
System.out.println(pageContent2);
}
两页(登录之前和登录之后)都一样打印出来。所以我在这里一定做错了。任何帮助将不胜感激。
凤凰求蛊
相关分类