由于第一次使用爬虫爬取网页内容,遇到一些特殊的情况也不是太会处理,这里把我遇到的一些情况和大家分享一下。
<pre name="code" class="java">public static String getPage(String s_url, String charset) {
if (s_url == null) {
return null;
}
try {
URL url = new URL(s_url);
BufferedReader bReader = new BufferedReader(new InputStreamReader(url.openStream(), charset));
String s;
StringBuffer sBuffer = new StringBuffer();
while ((s=bReader.readLine())!=null) {
sBuffer = sBuffer.append(s);
}
url = null;
return sBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
如上一段代码应该是获取网页源代码最简单的方式了,通过网页的url和编码方式直接获取网页的源代码,从而获取自己想要的信息。但是事情总没有想象的那么简单,现在的情况是这样的,我需要爬取的页面是京东三级类目下的商品信息,例如http://list.jd.com/list.html?cat=1620,1621,1627,但是通过上面的那种方式,无论设置那种编码结果返回的都是乱码,后来在访问的地址后面加了个?enc=utf-8,获取的页面终于不是乱码了,但是京东页面返回的结果却是“没有找到商品”,真的是伤心欲绝了。如果那位大神知道如何解决这种问题还请不吝告之。
好吧,废话说到这里,下面就是怎么用htmlunit爬虫工具来爬取京东页面了
<span style="white-space:pre"> </span>System.out.println("开始爬取页面了...");
//创建一个webclient
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
//htmlunit 对css和javascript的支持不好,所以请关闭之
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setTimeout(10000);
try{
//获取页面
HtmlPage page = webClient.getPage("http://list.jd.com/list.html?cat=1620,1621,1627");
List<?> divs = page.getByXPath("//div[@id='plist']");
HtmlDivision div = (HtmlDivision)divs.get(0);
HtmlUnorderedList ul = (HtmlUnorderedList)div.getFirstChild();
List<HtmlListItem> lis = ul.getHtmlElementsByTagName("li");
for(int i = 0; i < lis.size(); i ++){
HtmlListItem li = lis.get(i);
String index = li.getAttribute("index");
if(index == null || "".equals(index))
continue;
//打印出页面中的商品所对应的skuid
System.out.println("第" + li.getAttribute("index") + "个商品的skuid=" + li.getAttribute("data-sku"));
}
//获取该类目下的商品总页数
List<?> divs2 = page.getByXPath("//div[@id='J_bottomPage']");
HtmlDivision div2 = (HtmlDivision)divs2.get(0);
List<HtmlBold> b = div2.getHtmlElementsByTagName("b");
for(int i = 0; i < b.size(); i++){
String classname = b.get(i).getAttribute("class");
if(classname != null && !"".equals(classname)){
continue;
}
String pagetotal = b.get(i).getFirstChild().toString();
System.out.println("总页数为" + pagetotal);
}
System.out.println("哈哈");
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭webclient
<span style="white-space:pre"> </span>webClient.closeAllWindows();
}
如上已经能获取京东页面下该类目下的所有商品的skuid和总页数。后面的问题就很好解决了~
htmlunit相关的jar包下载地址:http://download.csdn.net/detail/zhourenfei17/8404589