[英]HtmlUnit - Button click issues
我正在用Java对服务器进行编码,对于服务器的一部分,我需要一个网络爬虫。 要抓取网站,我需要登录,并且当作为主要方法运行时,Web抓取工具可以正常工作,但是在服务器上运行时,单击按钮不会重定向到新页面。 这是代码。
String loginUrl="MY_URL";
WebClient web = new WebClient();
WebClientOptions options=web.getOptions();
web.getCookieManager().setCookiesEnabled(true);
options.setJavaScriptEnabled(true);
options.setPrintContentOnFailingStatusCode(false);
options.setCssEnabled(false);
options.setThrowExceptionOnFailingStatusCode(false);
options.setThrowExceptionOnScriptError(false);
options.setRedirectEnabled(true);
try {
final HtmlPage firstPage = (HtmlPage)web.getPage(loginUrl);
final HtmlForm form = firstPage.getForms().get(0);
final HtmlTextInput userNameField = form.getInputByName("USER");
userNameField.setValueAttribute("MY_USERNAME");
final HtmlPasswordInput passWordField = form.getInputByName("PASSWORD");
passWordField.setValueAttribute("MY_PASSWORD");
HtmlButton button =(HtmlButton)firstPage.getElementById("safeLoginbtn");
System.out.println(firstPage.getUrl().toString());
button.click();
System.out.println(web.getEnclosedPage().getUrl().toString());
}
catch(Exception e)
{
e.printStackTrace();
}
在main方法中运行时,两个打印语句显示两个不同的页面,分别是登录页面和登录后面的页面。 但是,当在服务器上运行时,这两个打印语句具有几乎相同的url,并且两者都是登录页面的url。 为什么会这样呢? 与在服务器上运行相比,为什么代码在主要方法中的行为不同?
如果服务器与Spring框架有任何关系,则该服务器将由该框架运行。
编辑:这里的例子:
WebClient webClient = new WebClient();
HtmlPage page1 = webClient.getPage("http://www.facebook.com");
HtmlForm form = page1.getForms().get(0);
HtmlSubmitInput button = (HtmlSubmitInput) form.getInputsByValue("Log In").get(0);
HtmlTextInput textField = form.getInputByName("email");
textField.setValueAttribute("email@email.com");
HtmlPasswordInput textField2 = form.getInputByName("pass");
textField2.setValueAttribute("MY_PASS");
HtmlPage page2 = button.click();
System.out.println(page2.asText());
这在Java应用程序的主要方法中有效,但是当通过Spring的预定注释在服务器上运行时,它将无法登录。
可能会有重定向的方式。 也许您可以执行以下操作:
HtmlPage pageAfterLogin = button.fireEvent("onclick").getNewPage();
System.out.println(pageAfterLogin.getUrl().toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.