最經對網路爬蟲比較感興趣,開始學習如何編寫網路爬蟲。看了一天的書,總結一下今天的學習成果。
網路爬蟲是一種基於一定規則自動抓取全球資訊網資訊的指令碼或則程式。本文是用Java語言編寫的一個利用指定的URL抓取網頁內容並將之儲存在本地的小程式。所謂網頁抓取就是把URL中指定的網路資源從網路流中讀取出來,儲存至本地。類似於是用程式類比瀏覽器的功能:把URL作為http請求的內容發送至伺服器,然後讀取伺服器的相應資源。java語言在網路編程上有天然的優勢,它把網路資源看做一種檔案,它對網路資源的訪問如同訪問本地資源一樣方便。它把請求與響應封裝成流。java.net.URL類可對相應的web伺服器發出請求並獲得回應,但實際的網路環境比較複雜,如果僅適用java.net中的API去類比瀏覽器功能,需要處理https協議、http返回狀態代碼等工作,編碼非常複雜。在實際項目中經常適用apache的HttpClient去類比瀏覽器抓取網頁內容。主要工作如下:
//建立一個用戶端,類似開啟一個瀏覽器
HttpClient httpClient = new HttpClient();
//建立一個get方法,類似在瀏覽器中輸入一個地址,path則為URL的值
GetMethod getMethod = new GetMethod(path);
//獲得響應的狀態代碼
int statusCode = httpClient.executeMethod(getMethod);
//得到返回的類容
String resoult = getMethod.gerResponseBodyAsString();
//釋放資源
getMethod.releaseConnection();
完整的網頁抓取程式如下:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
public class RetrivePage {
private static HttpClient httpClient = new HttpClient();
static GetMethod getmethod;
public static boolean downloadPage(String path) throws HttpException,
IOException {
getmethod = new GetMethod(path);
//獲得響應狀態代碼
int statusCode = httpClient.executeMethod(getmethod);
if(statusCode == HttpStatus.SC_OK){
System.out.println("response="+getmethod.getResponseBodyAsString());
//寫入本地檔案
FileWriter fwrite = new FileWriter("hello.txt");
String pageString = getmethod.getResponseBodyAsString();
getmethod.releaseConnection();
fwrite.write(pageString,0,pageString.length());
fwrite.flush();
//關閉檔案
fwrite.close();
//釋放資源
return true;
}
return false;
}
/**
* 測試代碼
*/
public static void main(String[] args) {
// 抓取制指定網頁,並將其輸出
try {
Scanner in = new Scanner(System.in);
System.out.println("Input the URL of the page you want to get:");
String path = in.next();
System.out.println("program start!");
RetrivePage.downloadPage(path);
System.out.println("Program end!");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}