日期:2014-05-17  浏览次数:20541 次

使用Cobra解析html, 及其提取table内容的例子。
    ?? ?以下方法读取一个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,请使用我的邀请码注册。<span style="font-family: arial, sans-serif, helvetica, tahoma; font-size: 16px; line-height: 24px;">很实用的免费文件网盘dropbox 可以访问了</span><span style="font-family: arial, sans-serif, helvetica, tahoma; font-size: 16px; font-weight: bold; line-height: 24px;">。</span>