2

我正在尝试使用具有有效用户名和密码的 HtmlUnit 执行登录。成功登录后,我想在结果页面上执行一些操作。问题是我无法通过登录阶段 - 我一直在同一页面上。奇怪的是,我记录了 HtmlUnit Scripter Firefox 插件的成功登录,然后重放了生成的代码——同样的问题。有任何想法吗?

这是代码:

<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("yacov.schondorf@gmail.com");

               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();
          }
     }

}
4

1 回答 1

0

看起来你的代码没问题。我手动尝试过,有时会登录,有时不会。问题出在登录操作后出现的弹出窗口中。您可以从页面上的 javascript 中看到它:

if ($("#ErrorDuplicationLogin").text() != '') 
  {       
   $(".PopUpContent").show();
   $(".pagePopBackground").show();                    

  }

});

因此,请尝试手动登录和注销,然后启动您的程序。也不要忘记使用 HtmlUnit 注销。谢谢你。

于 2013-07-26T12:57:11.240 回答