解析html中的table内容

阅读更多

最近接受了一个需求 需要解析网页源码来实现,所以写了一个解析网页中table的方法,给大家分享一下

这里面用到了htmlparser,下载地址:http://htmlparser.sourceforge.net/

 

URL url = new URL("http://"); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); Parser parser = new Parser(); parser.setConnection(connection); parser.setEncoding(parser.getEncoding()); NodeFilter filter_tab = new TagNameFilter("table"); NodeList nodelist = parser.parse(filter_tab); HashMap map = null; ArrayList list = new ArrayList(); if (nodelist != null && nodelist.size() > 0) { for (int i = 0; i < nodelist.size(); i++) { TableTag table = (TableTag) nodelist.elementAt(i); TableRow[] rows = table.getRows(); if (rows != null && rows.length > 0) { for (int j = 0; j < rows.length; j++) { map = new HashMap(); TableColumn[] cols = rows[j].getColumns(); for (int k = 0; k < cols.length; k++) { System.out.println(cols[k].toHtml().trim()); map.put(k, cols[k].toPlainTextString().trim()); } } } } }

你可能感兴趣的:(html,解析,htmlparser,网页源码解析,table)