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











