您的位置:首页 > 理论基础 > 计算机网络

HttpUnit 使用示例 抓取网页内容

2015-02-12 15:59 357 查看
最近在想如何从网页中抓取需要的数据出来, 直接用java提供的API太麻烦了, 在一些成熟的自动化测试web程序的类库中有可能需要的功能, 如HttpUnit, Watij, Selenium ; 现在试用了一下HttpUnit, 不是很方便, 只能找到有id的table元素, 没有id的还要自己处理response的流

public static void main(String[] args) {
WebClient webClient = new WebClient();

HtmlPage page = null;
try {
page = (HtmlPage) webClient.getPage("http://biz.cn.yahoo.com/stock.html");
} catch (FailingHttpStatusCodeException e) {

//e.printStackTrace();
} catch (MalformedURLException e) {

//e.printStackTrace();
} catch (IOException e) {

//e.printStackTrace();
}
WebResponse wr = page.getWebResponse();
HtmlDivision he = page.getHtmlElementById("stat1");
if (he.hasChildNodes()){
Iterator i = he.getChildElements().iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
System.out.println(he.getAttribute("id"));
//System.out.println(he.asXml());
Iterator<HtmlElement> i = page.getAllHtmlChildElements().iterator();
if(i.hasNext()){
HtmlElement h = i.next();
System.out.println(h.getNodeName());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: