一個簡單的基于java的網頁抓取程序

jopen 12年前發布 | 3K 次閱讀 Apache Cayenne 云計算

網絡爬蟲是一種基于一定規則自動抓取萬維網信息的腳本或則程序。本文是用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(); } } }</pre>
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!