使用Cobra解析html, 及其提取table内容的例子。

本文介绍了一种方法,通过使用Java代码从HTML格式的字符串中读取表格内容,并将其存储为数组列表,每项数组代表表格的一行数据。
    以下方法读取一个html格式的string,然后把其中的table内容读出,存入一个arralyst, 该list装入的是string[], 即每一个string[]元素代码table的一行。
 

	private list parsetable(string htmlstr) throws saxexception, ioexception {		reader reader = new stringreader(htmlstr);		inputsourceimpl inputsource = new inputsourceimpl(reader,				"aaa");		useragentcontext uacontext = new simpleuseragentcontext();		documentbuilderimpl builder = new documentbuilderimpl(uacontext);		document d = builder.parse(inputsource);		htmldocumentimpl document = (htmldocumentimpl) d;						nodelist  nl=document.getelementsbytagname("table");		arraylist<string[]> records=new arraylist<string[]>();		for (int i = 0; i < nl.getlength(); i++) {			htmltableelementimpl table=(htmltableelementimpl)nl.item(i);			htmlcollection rows=table.getrows();			for (int j = 0; j < rows.getlength(); j++) {				htmltablerowelementimpl row =(htmltablerowelementimpl)rows.item(j);				htmlcollection cells=row.getcells();				arraylist<string> cellsstr=new arraylist<string>();				for (int k = 0; k < cells.getlength(); k++) {					htmltablecellelementimpl cell =(htmltablecellelementimpl)cells.item(k);					cellsstr.add(cell.gettextcontent().tostring());				}				records.add(cellsstr.toarray(new string[0]));			}		}                return records;	}
  
    由于要解析js,必须要用到mozzila的rhino包。听说可以禁用js的解析,目前我还不知道如何做,没有仔细查api, 有知道的朋友说一声。
    附一个,由于需要足够大的<span style="font-family: arial, sans-serif, helvetica, tahoma; font-size: 16px; line-height: 24px;">dropbox</span>空间,如果你也正好需要一个dropbox,请使用我的[url=http://db.tt/xqivqgs]邀请码注册[/url]。<span style="font-family: arial, sans-serif, helvetica, tahoma; font-size: 16px; line-height: 24px;">[url=/blog/978914]很实用的免费文件网盘dropbox 可以访问了[/url]</span><span style="font-family: arial, sans-serif, helvetica, tahoma; font-size: 16px; font-weight: bold; line-height: 24px;">。</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值