使用web-harvest抓取分页数据(二)
除了使用上述方法外,还可以使用将不页的数据输出到不同的结构化好的XML文件里面,然后再进行读取的方法:
配置文件:
<var-def name="targetUrl">http://www.51zyr.com/tpl/index/hotel_list_web.do</var-def> <var name="page_num"/> <file action="write" path="hotel_page${page_num}.xml"> <template> <!]> </template> <loop item="item" index="i"> <list> <xpath expression="//table[@background='../images/dotline.gif']/tbody/tr"> <html-to-xml> <http url="${targetUrl}?pages=${page_num}"/> //这里根据从JAVA文件传过来的参数进行不同页面的查询抓取 </html-to-xml> </xpath> </list> <body> <xquery> <xq-param name="item"> <var name="item"/> </xq-param> <xq-expression><!) let $name := data($item//td) let $star := data($item//td) let $address := data($item//td) let $telephone := data($item//td) return <hotel> <num>{data($num)}</num> <name>{data($name)}</name> <star>{data($star)}</star> <address>{data($address)}</address> <telephone>{data($telephone)}</telephone> </hotel> ]]></xq-expression> </xquery> </body> </loop> <!]> </file>
接着是JAVA文件里面的关键代码:
public void QueryPath(int num) { try{ ScraperConfiguration config = new ScraperConfiguration("traveldata/config/hotel.xml"); Scraper scraper = new Scraper(config, "traveldata/output/hotel"); scraper.addVariableToContext("page_num", new String(""+num)); scraper.setDebug(true); long starttime = System.currentTimeMillis(); scraper.execute(); long endtime = System.currentTimeMillis(); System.out.println("Spent time:"+(endtime - starttime)); saveHotel(num); } catch(Exception e) { e.printStackTrace(); }}public void getContent(int pageNum)//循环调用{for(int i=1;i<=pageNum;i++){QueryPath(i);}}
页:
[1]