2013-04-17 86 views
0

我是Java新手,需要編寫各種Java應用程序來進行網頁抓取和網頁交互。Java和HTMLUnit:如何點擊提交按鈕?

我開始使用Selenium,但因爲它直接與瀏覽器交互,所以對我的使用並不實際。

我需要做下面的工作: 1.轉到特定的URL 2.在輸入字段中輸入一個郵政編碼 3.單擊提交按鈕 4.解析並保存特定的div標籤或重結果 - 查詢頁面。

我正在使用HTMLUnit和Eclipse。 我可以訪問網頁並通過引用表單然後輸入名稱在輸入中輸入郵編。 但是,當我嘗試點擊提交按鈕時,我得到一個ElementNotFoundException錯誤。

這裏的提交按鈕如何在網頁上實現的樣本:

 
type="submit" value="submit" name="submit">Enter post code 

這裏是我的代碼如下所示:

package htmlunittest; 

import java.io.IOException; 
import java.net.URL; 
import junit.framework.TestCase; 
import com.gargoylesoftware.htmlunit.BrowserVersion; 
import com.gargoylesoftware.htmlunit.Page; 
import com.gargoylesoftware.htmlunit.RefreshHandler; 
import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.HtmlDivision; 
import com.gargoylesoftware.htmlunit.html.HtmlButtonInput; 
import com.gargoylesoftware.htmlunit.html.HtmlForm; 
import com.gargoylesoftware.htmlunit.html.HtmlImage; 
import com.gargoylesoftware.htmlunit.html.HtmlInput; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; 
import com.gargoylesoftware.htmlunit.html.HtmlTextInput; 

public class htmlunittest extends TestCase{ 

@SuppressWarnings("deprecation") 
public static void main(String[] args) throws Exception 
{ 

    final WebClient webClient = new WebClient();    
    final HtmlPage startPage = webClient.getPage("http://www.testpage.com"); 

    final HtmlForm form = (HtmlForm) startPage.getForms().get(2); 

final HtmlTextInput textField = form.getInputByName("address"); 
    textField.setValueAttribute("my post code"); 

//throws ElementNotFoundException 
    final HtmlSubmitInput button = form.getInputByName("submit"); 

// Now submit the form by clicking the button and get back the second page. 
final HtmlPage page2 = button.click(); 
System.out.println(page2.getHtmlElementById("mainContent")); 

webClient.closeAllWindows(); 

} 
} 

可有人請點我在正確的方向至於如何通過HTMLUNIT點擊提交按鈕?

感謝

回答

0

這是一個有點難以發現這是爲什麼不是沒有,你試圖獲取整個頁面的工作。

我敢打賭,你沒有得到.get(2)的正確形式,順便說一句,通過這種方式獲取表單通常是一個糟糕的主意,因爲如果目標頁面稍微改變其源代碼,只是爲了添加一個高於該表單的表單你的刮板將不會再工作,因爲索引會有所不同。

+0

我試圖從以下網站檢索商店的開放時間:http://www.tesco.com/storeLocator/一旦我輸入郵政編碼:SW19 8YA,那麼我需要檢索商店的開放時間。 –