我正在尝试使用HtmlUnit 2.23单击登录按钮,使用DomElement
或executeJavaScript
,但它们都不起作用。有没有其他方法让它工作?这是代码:
@Test
public void noLogin() throws Exception {
final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED);
//see http://stackoverflow.com/questions/3600557/turning-htmlunit-warnings-off/18563576#18563576
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
//see http://stackoverflow.com/questions/18556200/htmlunit-button-click
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
final HtmlPage loginPage = webClient.getPage("https://sandbox.paydirekt.de/account/#/login");
loginPage.getElementById("username").setAttribute("value", "no");
loginPage.getElementById("password").setAttribute("value", "login");
//final HtmlPage welcomePage = ((DomElement)loginPage.getFirstByXPath("//button[@type='submit']")).click();
//see http://stackoverflow.com/questions/14474580/use-htmlunit-doesnt-work-button-click
//ScriptResult result = loginPage.executeJavaScript("javascript:document.getElementsByName('loginForm')[0].submit();");
ScriptResult result = loginPage.executeJavaScript("javascript:document.getElementsByClassName('loginBox__loginButton button button--full')[0].click()");
Page page = result.getNewPage();
if (page.isHtmlPage()) {
HtmlPage welcomePage = ((HtmlPage)page);
System.out.println(welcomePage.asText());
Assert.assertTrue(welcomePage.asText().contains("Benutzername oder Passwort nicht korrekt."));
}
webClient.close();
}
答案 0 :(得分:0)
您还可以使用HTMLUnit提供的连接包装器来手动检查每个请求和响应。这是一个例子
new WebConnectionWrapper(webClient) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if (request.getUrl().toExternalForm().contains("THE URL YOU WANT TO CHECK")) {
String content = response.getContentAsString("UTF-8");
//CHECK CONTENT HERE
WebResponseData data = new WebResponseData(content.getBytes("UTF-8"), response.getStatusCode(),
response.getStatusMessage(), response.getResponseHeaders());
response = new WebResponse(data, request, response.getLoadTime());
}
return response;
}
};