我在使用HTMLUNIT
(版本2.67.0)时尝试到达最后一页(登录后)时遇到问题
当我调试我的代码(一行一行),我可以把我的电子邮件和密码,并进入登录后的最后一页。但是,当我正常运行代码,我卡住了Wait... Redirecting to the Final Page
。我已经尝试了很多很多东西(创建新的线程来执行关键部分,同步等),但似乎没有什么工作,所以...
请帮忙!=)
下面是代码...
WebClient webClient = createWebClient();
try {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
HtmlPage page = webClient.getPage("https://pops.ons.org.br/ons.pop.federation");
threadWait(2);
HtmlSubmitInput button = (HtmlSubmitInput) page.getElementByName("submit.IdentificarUsuario");
threadWait(1);
HtmlTextInput textField1 = (HtmlTextInput) page.getElementById("username");
threadWait(1);
textField1.setValueAttribute("email@login.com");
threadWait(2);
button.click();
threadWait(3);
//Retrieve the page again, with the e-mail/user value, so I can enter the pwd
page = webClient.getPage("https://pops.ons.org.br/ons.pop.federation");
threadWait(3);
HtmlPasswordInput textField2 = (HtmlPasswordInput) page.getElementById("password");
threadWait(1);
HtmlSubmitInput button2 = (HtmlSubmitInput) page.getElementByName("submit.Signin");
threadWait(1);
textField2.setValueAttribute("myPwd123");
threadWait(2);
//The critical parts: when I click the "log in" btn
synchronized(button2) {
button2.click();
}
threadWait(5);
//The other critical part, when I retrieve the page again.
//When debbuging, this part gets me to the final page... when running normally,
// it gets stucked on the "Redirecting..." page
synchronized (page) {
page = webClient.getPage("https://pops.ons.org.br/ons.pop.federation");
}
threadWait(10);
System.out.println(page.asXml());
createWebClient()
方法:
public WebClient createWebClient() {
WebClient webClient = new WebClient(BrowserVersion.CHROME);
try {
//parâmetros do webclient
webClient.setJavaScriptTimeout(10000);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setTimeout(0);
webClient.getOptions().setRedirectEnabled(true);
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);
return webClient;
} catch (Exception e) {
logger.error("Error when creating WebClient: {}", e.getMessage());
return null;
}
}
threadWait()
方法:(它在每个动作之间实现一个最小值加上一个随机的时间间隔,以模拟真实的用户尝试登录)
public void threadWait(int segundos) {
try {
Random r = new Random();
int min = 1000;
int max = 5001;
int random = r.nextInt(max - min) + min;
segundos = (segundos * 1000) + random;
Thread.sleep(segundos);
} catch (Exception e) {
System.out.println("Error in Thread.sleep() ... " + e.getMessage());
}
}
阅读所有的StackOverflow
,这个想法是Thread.sleep(mills)
来模拟调试,正如你所看到的,我这样做了,但是,它就是不工作。
拜托,我到底怎么才能让这东西工作?
1条答案
按热度按时间zu0ti5jz1#
经过许多许多测试和失败...这是工作的代码...
configureWebClient()
方法: