除了使用上述方法外,还可以使用将不页的数据输出到不同的结构化好的XML文件里面,
然后再进行读取的方法:
配置文件:
接着是JAVA文件里面的关键代码:
然后再进行读取的方法:
配置文件:
<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>
<![CDATA[ <root> ]]>
</template>
<loop item="item" index="i">
<list>
<xpath expression="//table[@background='../images/dotline.gif'][1]/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><![CDATA[
declare variable $item as node() external;
let $num := data($item//td[1])
let $name := data($item//td[2])
let $star := data($item//td[3])
let $address := data($item//td[4])
let $telephone := data($item//td[5])
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>
<![CDATA[ </root> ]]>
</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);
}
}