4.2 處理頁面中的鏈接
這里的演示是找到頁面中的某一個鏈接,然后模擬用戶的單機行為,獲得它指向文件的內容。比如在我的頁面HelloWorld.html中有一個鏈接,它顯示的內容是TestLink,它指向我另一個頁面TestLink.htm. TestLink.htm里面只顯示TestLink.html幾個字符。
下面是處理代碼:
System.out.println("獲取頁面中鏈接指向頁面的內容:");
//建立一個WebConversation實例
WebConversation wc = new WebConversation();
//獲取響應對象
WebResponse resp = wc.getResponse( " http://localhost:6888/HelloWorld.html " );
//獲得頁面鏈接對象
WebLink link = resp.getLinkWith( "TestLink" );
//模擬用戶單擊事件
link.click();
//獲得當前的響應對象
WebResponse nextLink = wc.getCurrentPage();
![]()
//用getText方法獲取相應的全部內容
//用System.out.println將獲取的內容打印在控制臺上
System.out.println( nextLink.getText() );
4.3 處理頁面中的表格
表格是用來控制頁面顯示的常規對象,在HttpUnit中使用數組來處理頁面中的多個表格,你可以用resp.getTables()方法獲取頁面所有的表格對象。他們依照出現在頁面中的順序保存在一個數組里面。
[注意] Java中數組下標是從0開始的,所以取第一個表格應該是resp.getTables()[0],其他以此類推。
下面的例子演示如何從頁面中取出第一個表格的內容并且將他們循環顯示出來:
System.out.println("獲取頁面中表格的內容:");
//建立一個WebConversation實例
WebConversation wc = new WebConversation();
//獲取響應對象
WebResponse resp = wc.getResponse( " http://localhost:6888/HelloWorld.html " );
//獲得對應的表格對象
WebTable webTable = resp.getTables()[0];
//將表格對象的內容傳遞給字符串數組
String[][] datas = webTable.asText();
//循環顯示表格內容
int i = 0 ,j = 0;
int m = datas[0].length;
int n = datas.length;
while (i<n){
j=0;
while(j<m){
System.out.println("表格中第"+(i+1)+"行第"+(j+1)+"列的內容是:"+datas[j]);
++j;
}
++i;
}