2013-03-10 123 views
0

我正在製作一個小腳本,應該可以從頁面獲得大約300個鏈接,並將它們轉換爲快捷方式(全部保存在文件夾中)。從需要登錄的頁面獲取信息(Java)

我能夠從某些頁面獲取所需的所有鏈接,但有些網站需要我先登錄。

我試過HttpUnit,但我每次都只是失敗。到目前爲止,我只是把Html頁面放到一個inputStream中,並從那裏讀取(逐行查找我需要的內容),但是我不知道如何連接到網站或者在登錄部分時做任何事情。

這裏的HttpUnit的代碼,如果它可以幫助任何人:

final WebClient webClient = new WebClient(); 

// Get the first page 
final HtmlPage page1 = webClient.getPage("mywebsite"); 

ArrayList<HtmlForm> f; 
f = (ArrayList<HtmlForm>) page1.getForms(); 

System.out.println(f); 

// Get the form that we are dealing with and within that form, 
// find the submit button and the field that we want to change. 
final HtmlForm form = page1.getFirstByXPath("//form[@id='login']"); 

final HtmlSubmitInput button = form.getFirstByXPath("//input[@value='Login']"); 
final HtmlTextInput username = form.getFirstByXPath("//input[@id='username']"); 

// Change the value of the text field 
username.setValueAttribute("username"); 

final HtmlPasswordInput passField = form.getFirstByXPath("//input[@id='password']"); 

// Change the value of the text field 
passField.setValueAttribute("pass"); 

// Now submit the form by clicking the button and get back the second page. 
final HtmlPage page2 = button.click(); 

webClient.closeAllWindows(); 

請原諒我的不好的變量命名:P這是一個腳本只是爲我自己,所以我真的不打擾。

我在「final HtmlPage page2 = button.click();」上得到NullPointerException

在此先感謝。

回答

0

看來您的按鈕搜索失敗。這條線

final HtmlSubmitInput button = form.getFirstByXPath("//submit[@value='Login']"); 

後,我想補充

assert(button != null) : "Could not find the button"; 

而上(-ea參數在JVM)中運行帶有斷言你的應用程序,它會在那裏報告斷言失敗。

+0

謝謝,我改變了這部分,但它現在不給nullPointerException,但它仍然不起作用。 我得到這個: com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl通知 警告:遇到過時的內容類型:'text/javascript'。 2013年3月9日下午9:27:19 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler錯誤 和一個CSS錯誤和一個CSS警告。 該代碼是在我進入我想要達到的頁面之前。 – Shef 2013-03-10 05:28:56

+0

所以你改變了xpath查找,現在按鈕被正確找到了(即按鈕不再是'null')?新的錯誤在哪裏產生? – angelatlarge 2013-03-10 05:34:05