JAVA使用爬蟲抓取網站網頁內容的方法_java

來源:互聯網
上載者:User

本文執行個體講述了JAVA使用爬蟲抓取網站網頁內容的方法。分享給大家供大家參考。具體如下:

最近在用JAVA研究下耙梳技術,呵呵,入了個門,把自己的心得和大家分享下
以下提供二種方法,一種是用apache提供的包.另一種是用JAVA內建的.

代碼如下:

// 第一種方法//這種方法是用apache提供的包,簡單方便//但是要用到以下包:commons-codec-1.4.jar// commons-httpclient-3.1.jar// commons-logging-1.0.4.jarpublic static String createhttpClient(String url, String param) {  HttpClient client = new HttpClient();  String response = null;  String keyword = null;  PostMethod postMethod = new PostMethod(url);//  try {//   if (param != null)//    keyword = new String(param.getBytes("gb2312"), "ISO-8859-1");//  } catch (UnsupportedEncodingException e1) {//   // TODO Auto-generated catch block//   e1.printStackTrace();//  }  // NameValuePair[] data = { new NameValuePair("keyword", keyword) };  // // 將表單的值放入postMethod中  // postMethod.setRequestBody(data);  // 以上部分是帶參數抓取,我自己把它登出了.大家可以把登出消掉研究下  try {   int statusCode = client.executeMethod(postMethod);   response = new String(postMethod.getResponseBodyAsString()     .getBytes("ISO-8859-1"), "gb2312");     //這裡要注意下 gb2312要和你抓取網頁的編碼要一樣   String p = response.replaceAll("//&[a-zA-Z]{1,10};", "")     .replaceAll("<[^>]*>", "");//去掉網頁中帶有html語言的標籤   System.out.println(p);  } catch (Exception e) {   e.printStackTrace();  }  return response;}// 第二種方法// 這種方法是JAVA內建的URL來抓取網站內容public String getPageContent(String strUrl, String strPostRequest,   int maxLength) {  // 讀取結果網頁  StringBuffer buffer = new StringBuffer();  System.setProperty("sun.net.client.defaultConnectTimeout", "5000");  System.setProperty("sun.net.client.defaultReadTimeout", "5000");  try {   URL newUrl = new URL(strUrl);   HttpURLConnection hConnect = (HttpURLConnection) newUrl     .openConnection();   // POST方式的額外資料   if (strPostRequest.length() > 0) {    hConnect.setDoOutput(true);    OutputStreamWriter out = new OutputStreamWriter(hConnect      .getOutputStream());    out.write(strPostRequest);    out.flush();    out.close();   }   // 讀取內容   BufferedReader rd = new BufferedReader(new InputStreamReader(     hConnect.getInputStream()));   int ch;   for (int length = 0; (ch = rd.read()) > -1     && (maxLength <= 0 || length < maxLength); length++)    buffer.append((char) ch);   String s = buffer.toString();   s.replaceAll("//&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");   System.out.println(s);   rd.close();   hConnect.disconnect();   return buffer.toString().trim();  } catch (Exception e) {   // return "錯誤:讀取網頁失敗!";   //   return null;  }}

然後寫個測試類別:

public static void main(String[] args) {  String url = "http://www.jb51.net";  String keyword = "雲棲社區";  createhttpClient p = new createhttpClient();  String response = p.createhttpClient(url, keyword);  // 第一種方法  // p.getPageContent(url, "post", 100500);//第二種方法}

呵呵,看看控制台吧,是不是把網頁的內容擷取了

希望本文所述對大家的java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.