2014-11-03 66 views
0

我有以下代碼到我的網站,我想登錄到如下所示。我運行它時沒有錯誤消息,但它在最後返回的HTML是原始登錄頁面,這表明我沒有登錄。我嘗試過使用多個網站,同樣的事情一直在發生,所以我不知道是否在我想要的時候記錄下我的內容,或者當我轉到其他頁面時是否記得有關Cookie的內容。Java HTMLUnit登錄不起作用?

任何幫助將不勝感激。

import java.util.logging.Level; 
import org.jsoup.*; 
import org.jsoup.nodes.Document; 

import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.HtmlElement; 
import com.gargoylesoftware.htmlunit.html.HtmlOption; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 
import com.gargoylesoftware.htmlunit.html.HtmlSelect; 



public class testing { 
public static void main(String[] args) throws Exception { 

java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); 

final WebClient webClient = new WebClient(); 

final HtmlPage page = webClient.getPage("www.websiteneededtologinto.com"); 
HtmlElement usrname = page.getElementByName("Email"); 
usrname.click(); 
usrname.type("MYUSERNAME"); 
HtmlElement psswrd = page.getElementByName("Passwd"); 
psswrd.click(); 
psswrd.type("MYPASSWORD"); 
HtmlElement signin = page.getElementByName("signIn"); 
signin.click(); 



String html = Jsoup.connect("pagerequiringlogintoaccess.com").get().html(); 


System.out.println(html); 
    } 
    } 

回答

0

我以前也碰到這個問題,並解決它,我創建運行所有功能的方法:的setText,getEid,然後單擊。它們是:

public void click(HtmlElement el) throws Exception{ 
    page = el.click(); 
    } 

    public void setText(HtmlElement el, String text){ 
    HtmlTextInput input = (HtmlTextInput)el; 
    input.setText(text); 
    } 

public HtmlElement getEid(String id){ 
    HtmlElement rval = null; 
    boolean looking = true; 
    int counter = 0; 
    while(counter < elementRetryCount && looking){ 
     try{ 
     rval = page.getHtmlElementById(id); 
     looking = false; 
     } catch (Exception e){ 
     try { 
      Thread.sleep(elementRetryTimer * 1000); 
     } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
     } 
     } 
     counter ++; 
    } 
    return rval; 
    } 

要運行這些代碼將是這樣的:

scraper.setText(scraper.getEid("txtFromDate"), startingDate); 
scraper.click(scraper.getEid("btnSubmit")); 

希望這些變化有助於