下面是我簡單實現爬取指定網頁,並且儲存的簡單實現,其實有幾種方式可以實現,這裡慢慢添加該功能的幾種實現方式。
UrlConnection爬取實現
package html;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public class Spider { public static void main(String[] args) { String filepath = "d:/124.html"; String url_str = "http://www.hao123.com/"; URL url = null; try { url = new URL(url_str); } catch (MalformedURLException e) { e.printStackTrace(); } String charset = "utf-8"; int sec_cont = 1000; try { URLConnection url_con = url.openConnection(); url_con.setDoOutput(true); url_con.setReadTimeout(10 * sec_cont); url_con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); InputStream htm_in = url_con.getInputStream(); String htm_str = InputStream2String(htm_in,charset); saveHtml(filepath,htm_str); } catch (IOException e) { e.printStackTrace(); } } /** * Method: saveHtml * Description: save String to file * @param filepath * file path which need to be saved * @param str * string saved */ public static void saveHtml(String filepath, String str){ try { /*@SuppressWarnings("resource") FileWriter fw = new FileWriter(filepath); fw.write(str); fw.flush();*/ OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream(filepath, true), "utf-8"); outs.write(str); System.out.print(str); outs.close(); } catch (IOException e) { System.out.println("Error at save html..."); e.printStackTrace(); } } /** * Method: InputStream2String * Description: make InputStream to String * @param in_st * inputstream which need to be converted * @param charset * encoder of value * @throws IOException * if an error occurred */ public static String InputStream2String(InputStream in_st,String charset) throws IOException{ BufferedReader buff = new BufferedReader(new InputStreamReader(in_st, charset)); StringBuffer res = new StringBuffer(); String line = ""; while((line = buff.readLine()) != null){ res.append(line); } return res.toString(); }}
實現過程中,爬取的網頁的中文亂碼問題,是個比較麻煩的事情。
HttpClient爬取實現
HttpClient實現爬取網頁時,遇到了很多問題。其一,就是存在兩個版本的HttpClient,一個是sun內建的,另一個是apache開源的一個項目,似乎sun內建用的不太多,我也就沒有實現,而是採用了apache開源項目(以後說的HttpClient都是指apache的開源版本);其二,在使用HttpClient時,最新的版本已經不同於以前的版本,從HttpClient4.x版本後,匯入的包就已經不一樣了,從網上找的很多部分都是HttpClient3.x版本的,所以如果使用最新的版本,還是看協助檔案為好。
我用的是Eclipse,需要配置環境匯入引用包。
首先,下載HttpClient,地址是:http://hc.apache.org/downloads.cgi,我是用的事HttpClient4.2版本。
然後,解壓縮,找到了/lib檔案夾下的commons-codec-1.6.jar,commons-logging-1.1.1.jar,httpclient-4.2.5.jar,httpcore-4.2.4.jar(版本號碼根據下載的版本有所不同,還有其他的jar檔案,我這裡暫時用不到,所以先匯入必須的);
最後,將上面的jar檔案,加入classpath中,即右擊工程檔案 => Bulid Path => Configure Build Path => Add External Jar..,然後添加上面的包就可以了。
還用一種方法就是講上面的包,直接複製到工程檔案夾下的lib檔案夾中。
下面是實現代碼:
package html;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.*;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;public class SpiderHttpClient { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub String url_str = "http://www.hao123.com"; String charset = "utf-8"; String filepath = "d:/125.html"; HttpClient hc = new DefaultHttpClient(); HttpGet hg = new HttpGet(url_str); HttpResponse response = hc.execute(hg); HttpEntity entity = response.getEntity(); InputStream htm_in = null; if(entity != null){ System.out.println(entity.getContentLength()); htm_in = entity.getContent(); String htm_str = InputStream2String(htm_in,charset); saveHtml(filepath,htm_str); } } /** * Method: saveHtml * Description: save String to file * @param filepath * file path which need to be saved * @param str * string saved */ public static void saveHtml(String filepath, String str){ try { /*@SuppressWarnings("resource") FileWriter fw = new FileWriter(filepath); fw.write(str); fw.flush();*/ OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream(filepath, true), "utf-8"); outs.write(str); outs.close(); } catch (IOException e) { System.out.println("Error at save html..."); e.printStackTrace(); } } /** * Method: InputStream2String * Description: make InputStream to String * @param in_st * inputstream which need to be converted * @param charset * encoder of value * @throws IOException * if an error occurred */ public static String InputStream2String(InputStream in_st,String charset) throws IOException{ BufferedReader buff = new BufferedReader(new InputStreamReader(in_st, charset)); StringBuffer res = new StringBuffer(); String line = ""; while((line = buff.readLine()) != null){ res.append(line); } return res.toString(); }}
使用Httpclient實現網頁的爬取並儲存至本地
程式功能實現了爬取網頁頁面並且將結果儲存到本地,通過以爬取頁面出發,做一個小的爬蟲,分析出有利於自己的資訊,做定製化的處理。
import java.io.DataOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;public class CrawlPage { private static String filePath = "F:\\01_Code\\01_Eclipse\\AnalogLogin\\crawData\\"; private static String url = "http://www.huxiu.com/"; private static void saveToLocal(InputStream in, String filePath, String filename) throws IOException { File file = new File(filePath); if(!file.exists()) file.mkdirs(); DataOutputStream out = new DataOutputStream(new FileOutputStream( new File(filePath + filename))); int result; while((result=in.read())!=-1){ out.write(result); } out.flush(); out.close(); } public static void crawlPage() throws IOException { DefaultHttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); String fileName = "crawlPage.html"; //儲存到本地 saveToLocal(in, filePath + url.substring(5) + "\\", fileName); } public static void main(String[] args) throws IOException { crawlPage(); }}